echarts-en.js 2.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880
  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, textLineHeight, rich, 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.7';
  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. * Group a list by key.
  10264. *
  10265. * @param {Array} array
  10266. * @param {Function} getKey
  10267. * param {*} Array item
  10268. * return {string} key
  10269. * @return {Object} Result
  10270. * {Array}: keys,
  10271. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10272. */
  10273. function groupData(array, getKey) {
  10274. var buckets = createHashMap();
  10275. var keys = [];
  10276. each$1(array, function (item) {
  10277. var key = getKey(item);
  10278. (buckets.get(key)
  10279. || (keys.push(key), buckets.set(key, []))
  10280. ).push(item);
  10281. });
  10282. return {keys: keys, buckets: buckets};
  10283. }
  10284. /*
  10285. * Licensed to the Apache Software Foundation (ASF) under one
  10286. * or more contributor license agreements. See the NOTICE file
  10287. * distributed with this work for additional information
  10288. * regarding copyright ownership. The ASF licenses this file
  10289. * to you under the Apache License, Version 2.0 (the
  10290. * "License"); you may not use this file except in compliance
  10291. * with the License. You may obtain a copy of the License at
  10292. *
  10293. * http://www.apache.org/licenses/LICENSE-2.0
  10294. *
  10295. * Unless required by applicable law or agreed to in writing,
  10296. * software distributed under the License is distributed on an
  10297. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10298. * KIND, either express or implied. See the License for the
  10299. * specific language governing permissions and limitations
  10300. * under the License.
  10301. */
  10302. var TYPE_DELIMITER = '.';
  10303. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10304. /**
  10305. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10306. * @public
  10307. */
  10308. function parseClassType$1(componentType) {
  10309. var ret = {main: '', sub: ''};
  10310. if (componentType) {
  10311. componentType = componentType.split(TYPE_DELIMITER);
  10312. ret.main = componentType[0] || '';
  10313. ret.sub = componentType[1] || '';
  10314. }
  10315. return ret;
  10316. }
  10317. /**
  10318. * @public
  10319. */
  10320. function checkClassType(componentType) {
  10321. assert$1(
  10322. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10323. 'componentType "' + componentType + '" illegal'
  10324. );
  10325. }
  10326. /**
  10327. * @public
  10328. */
  10329. function enableClassExtend(RootClass, mandatoryMethods) {
  10330. RootClass.$constructor = RootClass;
  10331. RootClass.extend = function (proto) {
  10332. if (__DEV__) {
  10333. each$1(mandatoryMethods, function (method) {
  10334. if (!proto[method]) {
  10335. console.warn(
  10336. 'Method `' + method + '` should be implemented'
  10337. + (proto.type ? ' in ' + proto.type : '') + '.'
  10338. );
  10339. }
  10340. });
  10341. }
  10342. var superClass = this;
  10343. var ExtendedClass = function () {
  10344. if (!proto.$constructor) {
  10345. superClass.apply(this, arguments);
  10346. }
  10347. else {
  10348. proto.$constructor.apply(this, arguments);
  10349. }
  10350. };
  10351. extend(ExtendedClass.prototype, proto);
  10352. ExtendedClass.extend = this.extend;
  10353. ExtendedClass.superCall = superCall;
  10354. ExtendedClass.superApply = superApply;
  10355. inherits(ExtendedClass, this);
  10356. ExtendedClass.superClass = superClass;
  10357. return ExtendedClass;
  10358. };
  10359. }
  10360. var classBase = 0;
  10361. /**
  10362. * Can not use instanceof, consider different scope by
  10363. * cross domain or es module import in ec extensions.
  10364. * Mount a method "isInstance()" to Clz.
  10365. */
  10366. function enableClassCheck(Clz) {
  10367. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10368. Clz.prototype[classAttr] = true;
  10369. if (__DEV__) {
  10370. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10371. }
  10372. Clz.isInstance = function (obj) {
  10373. return !!(obj && obj[classAttr]);
  10374. };
  10375. }
  10376. // superCall should have class info, which can not be fetch from 'this'.
  10377. // Consider this case:
  10378. // class A has method f,
  10379. // class B inherits class A, overrides method f, f call superApply('f'),
  10380. // class C inherits class B, do not overrides method f,
  10381. // then when method of class C is called, dead loop occured.
  10382. function superCall(context, methodName) {
  10383. var args = slice(arguments, 2);
  10384. return this.superClass.prototype[methodName].apply(context, args);
  10385. }
  10386. function superApply(context, methodName, args) {
  10387. return this.superClass.prototype[methodName].apply(context, args);
  10388. }
  10389. /**
  10390. * @param {Object} entity
  10391. * @param {Object} options
  10392. * @param {boolean} [options.registerWhenExtend]
  10393. * @public
  10394. */
  10395. function enableClassManagement(entity, options) {
  10396. options = options || {};
  10397. /**
  10398. * Component model classes
  10399. * key: componentType,
  10400. * value:
  10401. * componentClass, when componentType is 'xxx'
  10402. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10403. * @type {Object}
  10404. */
  10405. var storage = {};
  10406. entity.registerClass = function (Clazz, componentType) {
  10407. if (componentType) {
  10408. checkClassType(componentType);
  10409. componentType = parseClassType$1(componentType);
  10410. if (!componentType.sub) {
  10411. if (__DEV__) {
  10412. if (storage[componentType.main]) {
  10413. console.warn(componentType.main + ' exists.');
  10414. }
  10415. }
  10416. storage[componentType.main] = Clazz;
  10417. }
  10418. else if (componentType.sub !== IS_CONTAINER) {
  10419. var container = makeContainer(componentType);
  10420. container[componentType.sub] = Clazz;
  10421. }
  10422. }
  10423. return Clazz;
  10424. };
  10425. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10426. var Clazz = storage[componentMainType];
  10427. if (Clazz && Clazz[IS_CONTAINER]) {
  10428. Clazz = subType ? Clazz[subType] : null;
  10429. }
  10430. if (throwWhenNotFound && !Clazz) {
  10431. throw new Error(
  10432. !subType
  10433. ? componentMainType + '.' + 'type should be specified.'
  10434. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10435. );
  10436. }
  10437. return Clazz;
  10438. };
  10439. entity.getClassesByMainType = function (componentType) {
  10440. componentType = parseClassType$1(componentType);
  10441. var result = [];
  10442. var obj = storage[componentType.main];
  10443. if (obj && obj[IS_CONTAINER]) {
  10444. each$1(obj, function (o, type) {
  10445. type !== IS_CONTAINER && result.push(o);
  10446. });
  10447. }
  10448. else {
  10449. result.push(obj);
  10450. }
  10451. return result;
  10452. };
  10453. entity.hasClass = function (componentType) {
  10454. // Just consider componentType.main.
  10455. componentType = parseClassType$1(componentType);
  10456. return !!storage[componentType.main];
  10457. };
  10458. /**
  10459. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10460. */
  10461. entity.getAllClassMainTypes = function () {
  10462. var types = [];
  10463. each$1(storage, function (obj, type) {
  10464. types.push(type);
  10465. });
  10466. return types;
  10467. };
  10468. /**
  10469. * If a main type is container and has sub types
  10470. * @param {string} mainType
  10471. * @return {boolean}
  10472. */
  10473. entity.hasSubTypes = function (componentType) {
  10474. componentType = parseClassType$1(componentType);
  10475. var obj = storage[componentType.main];
  10476. return obj && obj[IS_CONTAINER];
  10477. };
  10478. entity.parseClassType = parseClassType$1;
  10479. function makeContainer(componentType) {
  10480. var container = storage[componentType.main];
  10481. if (!container || !container[IS_CONTAINER]) {
  10482. container = storage[componentType.main] = {};
  10483. container[IS_CONTAINER] = true;
  10484. }
  10485. return container;
  10486. }
  10487. if (options.registerWhenExtend) {
  10488. var originalExtend = entity.extend;
  10489. if (originalExtend) {
  10490. entity.extend = function (proto) {
  10491. var ExtendedClass = originalExtend.call(this, proto);
  10492. return entity.registerClass(ExtendedClass, proto.type);
  10493. };
  10494. }
  10495. }
  10496. return entity;
  10497. }
  10498. /**
  10499. * @param {string|Array.<string>} properties
  10500. */
  10501. /*
  10502. * Licensed to the Apache Software Foundation (ASF) under one
  10503. * or more contributor license agreements. See the NOTICE file
  10504. * distributed with this work for additional information
  10505. * regarding copyright ownership. The ASF licenses this file
  10506. * to you under the Apache License, Version 2.0 (the
  10507. * "License"); you may not use this file except in compliance
  10508. * with the License. You may obtain a copy of the License at
  10509. *
  10510. * http://www.apache.org/licenses/LICENSE-2.0
  10511. *
  10512. * Unless required by applicable law or agreed to in writing,
  10513. * software distributed under the License is distributed on an
  10514. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10515. * KIND, either express or implied. See the License for the
  10516. * specific language governing permissions and limitations
  10517. * under the License.
  10518. */
  10519. // TODO Parse shadow style
  10520. // TODO Only shallow path support
  10521. var makeStyleMapper = function (properties) {
  10522. // Normalize
  10523. for (var i = 0; i < properties.length; i++) {
  10524. if (!properties[i][1]) {
  10525. properties[i][1] = properties[i][0];
  10526. }
  10527. }
  10528. return function (model, excludes, includes) {
  10529. var style = {};
  10530. for (var i = 0; i < properties.length; i++) {
  10531. var propName = properties[i][1];
  10532. if ((excludes && indexOf(excludes, propName) >= 0)
  10533. || (includes && indexOf(includes, propName) < 0)
  10534. ) {
  10535. continue;
  10536. }
  10537. var val = model.getShallow(propName);
  10538. if (val != null) {
  10539. style[properties[i][0]] = val;
  10540. }
  10541. }
  10542. return style;
  10543. };
  10544. };
  10545. /*
  10546. * Licensed to the Apache Software Foundation (ASF) under one
  10547. * or more contributor license agreements. See the NOTICE file
  10548. * distributed with this work for additional information
  10549. * regarding copyright ownership. The ASF licenses this file
  10550. * to you under the Apache License, Version 2.0 (the
  10551. * "License"); you may not use this file except in compliance
  10552. * with the License. You may obtain a copy of the License at
  10553. *
  10554. * http://www.apache.org/licenses/LICENSE-2.0
  10555. *
  10556. * Unless required by applicable law or agreed to in writing,
  10557. * software distributed under the License is distributed on an
  10558. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10559. * KIND, either express or implied. See the License for the
  10560. * specific language governing permissions and limitations
  10561. * under the License.
  10562. */
  10563. var getLineStyle = makeStyleMapper(
  10564. [
  10565. ['lineWidth', 'width'],
  10566. ['stroke', 'color'],
  10567. ['opacity'],
  10568. ['shadowBlur'],
  10569. ['shadowOffsetX'],
  10570. ['shadowOffsetY'],
  10571. ['shadowColor']
  10572. ]
  10573. );
  10574. var lineStyleMixin = {
  10575. getLineStyle: function (excludes) {
  10576. var style = getLineStyle(this, excludes);
  10577. var lineDash = this.getLineDash(style.lineWidth);
  10578. lineDash && (style.lineDash = lineDash);
  10579. return style;
  10580. },
  10581. getLineDash: function (lineWidth) {
  10582. if (lineWidth == null) {
  10583. lineWidth = 1;
  10584. }
  10585. var lineType = this.get('type');
  10586. var dotSize = Math.max(lineWidth, 2);
  10587. var dashSize = lineWidth * 4;
  10588. return (lineType === 'solid' || lineType == null) ? null
  10589. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10590. }
  10591. };
  10592. /*
  10593. * Licensed to the Apache Software Foundation (ASF) under one
  10594. * or more contributor license agreements. See the NOTICE file
  10595. * distributed with this work for additional information
  10596. * regarding copyright ownership. The ASF licenses this file
  10597. * to you under the Apache License, Version 2.0 (the
  10598. * "License"); you may not use this file except in compliance
  10599. * with the License. You may obtain a copy of the License at
  10600. *
  10601. * http://www.apache.org/licenses/LICENSE-2.0
  10602. *
  10603. * Unless required by applicable law or agreed to in writing,
  10604. * software distributed under the License is distributed on an
  10605. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10606. * KIND, either express or implied. See the License for the
  10607. * specific language governing permissions and limitations
  10608. * under the License.
  10609. */
  10610. var getAreaStyle = makeStyleMapper(
  10611. [
  10612. ['fill', 'color'],
  10613. ['shadowBlur'],
  10614. ['shadowOffsetX'],
  10615. ['shadowOffsetY'],
  10616. ['opacity'],
  10617. ['shadowColor']
  10618. ]
  10619. );
  10620. var areaStyleMixin = {
  10621. getAreaStyle: function (excludes, includes) {
  10622. return getAreaStyle(this, excludes, includes);
  10623. }
  10624. };
  10625. /**
  10626. * 曲线辅助模块
  10627. * @module zrender/core/curve
  10628. * @author pissang(https://www.github.com/pissang)
  10629. */
  10630. var mathPow = Math.pow;
  10631. var mathSqrt$2 = Math.sqrt;
  10632. var EPSILON$1 = 1e-8;
  10633. var EPSILON_NUMERIC = 1e-4;
  10634. var THREE_SQRT = mathSqrt$2(3);
  10635. var ONE_THIRD = 1 / 3;
  10636. // 临时变量
  10637. var _v0 = create();
  10638. var _v1 = create();
  10639. var _v2 = create();
  10640. function isAroundZero(val) {
  10641. return val > -EPSILON$1 && val < EPSILON$1;
  10642. }
  10643. function isNotAroundZero$1(val) {
  10644. return val > EPSILON$1 || val < -EPSILON$1;
  10645. }
  10646. /**
  10647. * 计算三次贝塞尔值
  10648. * @memberOf module:zrender/core/curve
  10649. * @param {number} p0
  10650. * @param {number} p1
  10651. * @param {number} p2
  10652. * @param {number} p3
  10653. * @param {number} t
  10654. * @return {number}
  10655. */
  10656. function cubicAt(p0, p1, p2, p3, t) {
  10657. var onet = 1 - t;
  10658. return onet * onet * (onet * p0 + 3 * t * p1)
  10659. + t * t * (t * p3 + 3 * onet * p2);
  10660. }
  10661. /**
  10662. * 计算三次贝塞尔导数值
  10663. * @memberOf module:zrender/core/curve
  10664. * @param {number} p0
  10665. * @param {number} p1
  10666. * @param {number} p2
  10667. * @param {number} p3
  10668. * @param {number} t
  10669. * @return {number}
  10670. */
  10671. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10672. var onet = 1 - t;
  10673. return 3 * (
  10674. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10675. + (p3 - p2) * t * t
  10676. );
  10677. }
  10678. /**
  10679. * 计算三次贝塞尔方程根,使用盛金公式
  10680. * @memberOf module:zrender/core/curve
  10681. * @param {number} p0
  10682. * @param {number} p1
  10683. * @param {number} p2
  10684. * @param {number} p3
  10685. * @param {number} val
  10686. * @param {Array.<number>} roots
  10687. * @return {number} 有效根数目
  10688. */
  10689. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10690. // Evaluate roots of cubic functions
  10691. var a = p3 + 3 * (p1 - p2) - p0;
  10692. var b = 3 * (p2 - p1 * 2 + p0);
  10693. var c = 3 * (p1 - p0);
  10694. var d = p0 - val;
  10695. var A = b * b - 3 * a * c;
  10696. var B = b * c - 9 * a * d;
  10697. var C = c * c - 3 * b * d;
  10698. var n = 0;
  10699. if (isAroundZero(A) && isAroundZero(B)) {
  10700. if (isAroundZero(b)) {
  10701. roots[0] = 0;
  10702. }
  10703. else {
  10704. var t1 = -c / b; //t1, t2, t3, b is not zero
  10705. if (t1 >= 0 && t1 <= 1) {
  10706. roots[n++] = t1;
  10707. }
  10708. }
  10709. }
  10710. else {
  10711. var disc = B * B - 4 * A * C;
  10712. if (isAroundZero(disc)) {
  10713. var K = B / A;
  10714. var t1 = -b / a + K; // t1, a is not zero
  10715. var t2 = -K / 2; // t2, t3
  10716. if (t1 >= 0 && t1 <= 1) {
  10717. roots[n++] = t1;
  10718. }
  10719. if (t2 >= 0 && t2 <= 1) {
  10720. roots[n++] = t2;
  10721. }
  10722. }
  10723. else if (disc > 0) {
  10724. var discSqrt = mathSqrt$2(disc);
  10725. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10726. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10727. if (Y1 < 0) {
  10728. Y1 = -mathPow(-Y1, ONE_THIRD);
  10729. }
  10730. else {
  10731. Y1 = mathPow(Y1, ONE_THIRD);
  10732. }
  10733. if (Y2 < 0) {
  10734. Y2 = -mathPow(-Y2, ONE_THIRD);
  10735. }
  10736. else {
  10737. Y2 = mathPow(Y2, ONE_THIRD);
  10738. }
  10739. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10740. if (t1 >= 0 && t1 <= 1) {
  10741. roots[n++] = t1;
  10742. }
  10743. }
  10744. else {
  10745. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10746. var theta = Math.acos(T) / 3;
  10747. var ASqrt = mathSqrt$2(A);
  10748. var tmp = Math.cos(theta);
  10749. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10750. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10751. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10752. if (t1 >= 0 && t1 <= 1) {
  10753. roots[n++] = t1;
  10754. }
  10755. if (t2 >= 0 && t2 <= 1) {
  10756. roots[n++] = t2;
  10757. }
  10758. if (t3 >= 0 && t3 <= 1) {
  10759. roots[n++] = t3;
  10760. }
  10761. }
  10762. }
  10763. return n;
  10764. }
  10765. /**
  10766. * 计算三次贝塞尔方程极限值的位置
  10767. * @memberOf module:zrender/core/curve
  10768. * @param {number} p0
  10769. * @param {number} p1
  10770. * @param {number} p2
  10771. * @param {number} p3
  10772. * @param {Array.<number>} extrema
  10773. * @return {number} 有效数目
  10774. */
  10775. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10776. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10777. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10778. var c = 3 * p1 - 3 * p0;
  10779. var n = 0;
  10780. if (isAroundZero(a)) {
  10781. if (isNotAroundZero$1(b)) {
  10782. var t1 = -c / b;
  10783. if (t1 >= 0 && t1 <= 1) {
  10784. extrema[n++] = t1;
  10785. }
  10786. }
  10787. }
  10788. else {
  10789. var disc = b * b - 4 * a * c;
  10790. if (isAroundZero(disc)) {
  10791. extrema[0] = -b / (2 * a);
  10792. }
  10793. else if (disc > 0) {
  10794. var discSqrt = mathSqrt$2(disc);
  10795. var t1 = (-b + discSqrt) / (2 * a);
  10796. var t2 = (-b - discSqrt) / (2 * a);
  10797. if (t1 >= 0 && t1 <= 1) {
  10798. extrema[n++] = t1;
  10799. }
  10800. if (t2 >= 0 && t2 <= 1) {
  10801. extrema[n++] = t2;
  10802. }
  10803. }
  10804. }
  10805. return n;
  10806. }
  10807. /**
  10808. * 细分三次贝塞尔曲线
  10809. * @memberOf module:zrender/core/curve
  10810. * @param {number} p0
  10811. * @param {number} p1
  10812. * @param {number} p2
  10813. * @param {number} p3
  10814. * @param {number} t
  10815. * @param {Array.<number>} out
  10816. */
  10817. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10818. var p01 = (p1 - p0) * t + p0;
  10819. var p12 = (p2 - p1) * t + p1;
  10820. var p23 = (p3 - p2) * t + p2;
  10821. var p012 = (p12 - p01) * t + p01;
  10822. var p123 = (p23 - p12) * t + p12;
  10823. var p0123 = (p123 - p012) * t + p012;
  10824. // Seg0
  10825. out[0] = p0;
  10826. out[1] = p01;
  10827. out[2] = p012;
  10828. out[3] = p0123;
  10829. // Seg1
  10830. out[4] = p0123;
  10831. out[5] = p123;
  10832. out[6] = p23;
  10833. out[7] = p3;
  10834. }
  10835. /**
  10836. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10837. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10838. * @param {number} x0
  10839. * @param {number} y0
  10840. * @param {number} x1
  10841. * @param {number} y1
  10842. * @param {number} x2
  10843. * @param {number} y2
  10844. * @param {number} x3
  10845. * @param {number} y3
  10846. * @param {number} x
  10847. * @param {number} y
  10848. * @param {Array.<number>} [out] 投射点
  10849. * @return {number}
  10850. */
  10851. function cubicProjectPoint(
  10852. x0, y0, x1, y1, x2, y2, x3, y3,
  10853. x, y, out
  10854. ) {
  10855. // http://pomax.github.io/bezierinfo/#projections
  10856. var t;
  10857. var interval = 0.005;
  10858. var d = Infinity;
  10859. var prev;
  10860. var next;
  10861. var d1;
  10862. var d2;
  10863. _v0[0] = x;
  10864. _v0[1] = y;
  10865. // 先粗略估计一下可能的最小距离的 t 值
  10866. // PENDING
  10867. for (var _t = 0; _t < 1; _t += 0.05) {
  10868. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10869. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10870. d1 = distSquare(_v0, _v1);
  10871. if (d1 < d) {
  10872. t = _t;
  10873. d = d1;
  10874. }
  10875. }
  10876. d = Infinity;
  10877. // At most 32 iteration
  10878. for (var i = 0; i < 32; i++) {
  10879. if (interval < EPSILON_NUMERIC) {
  10880. break;
  10881. }
  10882. prev = t - interval;
  10883. next = t + interval;
  10884. // t - interval
  10885. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10886. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10887. d1 = distSquare(_v1, _v0);
  10888. if (prev >= 0 && d1 < d) {
  10889. t = prev;
  10890. d = d1;
  10891. }
  10892. else {
  10893. // t + interval
  10894. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10895. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10896. d2 = distSquare(_v2, _v0);
  10897. if (next <= 1 && d2 < d) {
  10898. t = next;
  10899. d = d2;
  10900. }
  10901. else {
  10902. interval *= 0.5;
  10903. }
  10904. }
  10905. }
  10906. // t
  10907. if (out) {
  10908. out[0] = cubicAt(x0, x1, x2, x3, t);
  10909. out[1] = cubicAt(y0, y1, y2, y3, t);
  10910. }
  10911. // console.log(interval, i);
  10912. return mathSqrt$2(d);
  10913. }
  10914. /**
  10915. * 计算二次方贝塞尔值
  10916. * @param {number} p0
  10917. * @param {number} p1
  10918. * @param {number} p2
  10919. * @param {number} t
  10920. * @return {number}
  10921. */
  10922. function quadraticAt(p0, p1, p2, t) {
  10923. var onet = 1 - t;
  10924. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10925. }
  10926. /**
  10927. * 计算二次方贝塞尔导数值
  10928. * @param {number} p0
  10929. * @param {number} p1
  10930. * @param {number} p2
  10931. * @param {number} t
  10932. * @return {number}
  10933. */
  10934. function quadraticDerivativeAt(p0, p1, p2, t) {
  10935. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10936. }
  10937. /**
  10938. * 计算二次方贝塞尔方程根
  10939. * @param {number} p0
  10940. * @param {number} p1
  10941. * @param {number} p2
  10942. * @param {number} t
  10943. * @param {Array.<number>} roots
  10944. * @return {number} 有效根数目
  10945. */
  10946. function quadraticRootAt(p0, p1, p2, val, roots) {
  10947. var a = p0 - 2 * p1 + p2;
  10948. var b = 2 * (p1 - p0);
  10949. var c = p0 - val;
  10950. var n = 0;
  10951. if (isAroundZero(a)) {
  10952. if (isNotAroundZero$1(b)) {
  10953. var t1 = -c / b;
  10954. if (t1 >= 0 && t1 <= 1) {
  10955. roots[n++] = t1;
  10956. }
  10957. }
  10958. }
  10959. else {
  10960. var disc = b * b - 4 * a * c;
  10961. if (isAroundZero(disc)) {
  10962. var t1 = -b / (2 * a);
  10963. if (t1 >= 0 && t1 <= 1) {
  10964. roots[n++] = t1;
  10965. }
  10966. }
  10967. else if (disc > 0) {
  10968. var discSqrt = mathSqrt$2(disc);
  10969. var t1 = (-b + discSqrt) / (2 * a);
  10970. var t2 = (-b - discSqrt) / (2 * a);
  10971. if (t1 >= 0 && t1 <= 1) {
  10972. roots[n++] = t1;
  10973. }
  10974. if (t2 >= 0 && t2 <= 1) {
  10975. roots[n++] = t2;
  10976. }
  10977. }
  10978. }
  10979. return n;
  10980. }
  10981. /**
  10982. * 计算二次贝塞尔方程极限值
  10983. * @memberOf module:zrender/core/curve
  10984. * @param {number} p0
  10985. * @param {number} p1
  10986. * @param {number} p2
  10987. * @return {number}
  10988. */
  10989. function quadraticExtremum(p0, p1, p2) {
  10990. var divider = p0 + p2 - 2 * p1;
  10991. if (divider === 0) {
  10992. // p1 is center of p0 and p2
  10993. return 0.5;
  10994. }
  10995. else {
  10996. return (p0 - p1) / divider;
  10997. }
  10998. }
  10999. /**
  11000. * 细分二次贝塞尔曲线
  11001. * @memberOf module:zrender/core/curve
  11002. * @param {number} p0
  11003. * @param {number} p1
  11004. * @param {number} p2
  11005. * @param {number} t
  11006. * @param {Array.<number>} out
  11007. */
  11008. function quadraticSubdivide(p0, p1, p2, t, out) {
  11009. var p01 = (p1 - p0) * t + p0;
  11010. var p12 = (p2 - p1) * t + p1;
  11011. var p012 = (p12 - p01) * t + p01;
  11012. // Seg0
  11013. out[0] = p0;
  11014. out[1] = p01;
  11015. out[2] = p012;
  11016. // Seg1
  11017. out[3] = p012;
  11018. out[4] = p12;
  11019. out[5] = p2;
  11020. }
  11021. /**
  11022. * 投射点到二次贝塞尔曲线上,返回投射距离。
  11023. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11024. * @param {number} x0
  11025. * @param {number} y0
  11026. * @param {number} x1
  11027. * @param {number} y1
  11028. * @param {number} x2
  11029. * @param {number} y2
  11030. * @param {number} x
  11031. * @param {number} y
  11032. * @param {Array.<number>} out 投射点
  11033. * @return {number}
  11034. */
  11035. function quadraticProjectPoint(
  11036. x0, y0, x1, y1, x2, y2,
  11037. x, y, out
  11038. ) {
  11039. // http://pomax.github.io/bezierinfo/#projections
  11040. var t;
  11041. var interval = 0.005;
  11042. var d = Infinity;
  11043. _v0[0] = x;
  11044. _v0[1] = y;
  11045. // 先粗略估计一下可能的最小距离的 t 值
  11046. // PENDING
  11047. for (var _t = 0; _t < 1; _t += 0.05) {
  11048. _v1[0] = quadraticAt(x0, x1, x2, _t);
  11049. _v1[1] = quadraticAt(y0, y1, y2, _t);
  11050. var d1 = distSquare(_v0, _v1);
  11051. if (d1 < d) {
  11052. t = _t;
  11053. d = d1;
  11054. }
  11055. }
  11056. d = Infinity;
  11057. // At most 32 iteration
  11058. for (var i = 0; i < 32; i++) {
  11059. if (interval < EPSILON_NUMERIC) {
  11060. break;
  11061. }
  11062. var prev = t - interval;
  11063. var next = t + interval;
  11064. // t - interval
  11065. _v1[0] = quadraticAt(x0, x1, x2, prev);
  11066. _v1[1] = quadraticAt(y0, y1, y2, prev);
  11067. var d1 = distSquare(_v1, _v0);
  11068. if (prev >= 0 && d1 < d) {
  11069. t = prev;
  11070. d = d1;
  11071. }
  11072. else {
  11073. // t + interval
  11074. _v2[0] = quadraticAt(x0, x1, x2, next);
  11075. _v2[1] = quadraticAt(y0, y1, y2, next);
  11076. var d2 = distSquare(_v2, _v0);
  11077. if (next <= 1 && d2 < d) {
  11078. t = next;
  11079. d = d2;
  11080. }
  11081. else {
  11082. interval *= 0.5;
  11083. }
  11084. }
  11085. }
  11086. // t
  11087. if (out) {
  11088. out[0] = quadraticAt(x0, x1, x2, t);
  11089. out[1] = quadraticAt(y0, y1, y2, t);
  11090. }
  11091. // console.log(interval, i);
  11092. return mathSqrt$2(d);
  11093. }
  11094. /**
  11095. * @author Yi Shen(https://github.com/pissang)
  11096. */
  11097. var mathMin$3 = Math.min;
  11098. var mathMax$3 = Math.max;
  11099. var mathSin$2 = Math.sin;
  11100. var mathCos$2 = Math.cos;
  11101. var PI2 = Math.PI * 2;
  11102. var start = create();
  11103. var end = create();
  11104. var extremity = create();
  11105. /**
  11106. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11107. * @module zrender/core/bbox
  11108. * @param {Array<Object>} points 顶点数组
  11109. * @param {number} min
  11110. * @param {number} max
  11111. */
  11112. function fromPoints(points, min$$1, max$$1) {
  11113. if (points.length === 0) {
  11114. return;
  11115. }
  11116. var p = points[0];
  11117. var left = p[0];
  11118. var right = p[0];
  11119. var top = p[1];
  11120. var bottom = p[1];
  11121. var i;
  11122. for (i = 1; i < points.length; i++) {
  11123. p = points[i];
  11124. left = mathMin$3(left, p[0]);
  11125. right = mathMax$3(right, p[0]);
  11126. top = mathMin$3(top, p[1]);
  11127. bottom = mathMax$3(bottom, p[1]);
  11128. }
  11129. min$$1[0] = left;
  11130. min$$1[1] = top;
  11131. max$$1[0] = right;
  11132. max$$1[1] = bottom;
  11133. }
  11134. /**
  11135. * @memberOf module:zrender/core/bbox
  11136. * @param {number} x0
  11137. * @param {number} y0
  11138. * @param {number} x1
  11139. * @param {number} y1
  11140. * @param {Array.<number>} min
  11141. * @param {Array.<number>} max
  11142. */
  11143. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11144. min$$1[0] = mathMin$3(x0, x1);
  11145. min$$1[1] = mathMin$3(y0, y1);
  11146. max$$1[0] = mathMax$3(x0, x1);
  11147. max$$1[1] = mathMax$3(y0, y1);
  11148. }
  11149. var xDim = [];
  11150. var yDim = [];
  11151. /**
  11152. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11153. * @memberOf module:zrender/core/bbox
  11154. * @param {number} x0
  11155. * @param {number} y0
  11156. * @param {number} x1
  11157. * @param {number} y1
  11158. * @param {number} x2
  11159. * @param {number} y2
  11160. * @param {number} x3
  11161. * @param {number} y3
  11162. * @param {Array.<number>} min
  11163. * @param {Array.<number>} max
  11164. */
  11165. function fromCubic(
  11166. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11167. ) {
  11168. var cubicExtrema$$1 = cubicExtrema;
  11169. var cubicAt$$1 = cubicAt;
  11170. var i;
  11171. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11172. min$$1[0] = Infinity;
  11173. min$$1[1] = Infinity;
  11174. max$$1[0] = -Infinity;
  11175. max$$1[1] = -Infinity;
  11176. for (i = 0; i < n; i++) {
  11177. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11178. min$$1[0] = mathMin$3(x, min$$1[0]);
  11179. max$$1[0] = mathMax$3(x, max$$1[0]);
  11180. }
  11181. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11182. for (i = 0; i < n; i++) {
  11183. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11184. min$$1[1] = mathMin$3(y, min$$1[1]);
  11185. max$$1[1] = mathMax$3(y, max$$1[1]);
  11186. }
  11187. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11188. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11189. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11190. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11191. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11192. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11193. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11194. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11195. }
  11196. /**
  11197. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11198. * @memberOf module:zrender/core/bbox
  11199. * @param {number} x0
  11200. * @param {number} y0
  11201. * @param {number} x1
  11202. * @param {number} y1
  11203. * @param {number} x2
  11204. * @param {number} y2
  11205. * @param {Array.<number>} min
  11206. * @param {Array.<number>} max
  11207. */
  11208. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11209. var quadraticExtremum$$1 = quadraticExtremum;
  11210. var quadraticAt$$1 = quadraticAt;
  11211. // Find extremities, where derivative in x dim or y dim is zero
  11212. var tx =
  11213. mathMax$3(
  11214. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11215. );
  11216. var ty =
  11217. mathMax$3(
  11218. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11219. );
  11220. var x = quadraticAt$$1(x0, x1, x2, tx);
  11221. var y = quadraticAt$$1(y0, y1, y2, ty);
  11222. min$$1[0] = mathMin$3(x0, x2, x);
  11223. min$$1[1] = mathMin$3(y0, y2, y);
  11224. max$$1[0] = mathMax$3(x0, x2, x);
  11225. max$$1[1] = mathMax$3(y0, y2, y);
  11226. }
  11227. /**
  11228. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11229. * @method
  11230. * @memberOf module:zrender/core/bbox
  11231. * @param {number} x
  11232. * @param {number} y
  11233. * @param {number} rx
  11234. * @param {number} ry
  11235. * @param {number} startAngle
  11236. * @param {number} endAngle
  11237. * @param {number} anticlockwise
  11238. * @param {Array.<number>} min
  11239. * @param {Array.<number>} max
  11240. */
  11241. function fromArc(
  11242. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11243. ) {
  11244. var vec2Min = min;
  11245. var vec2Max = max;
  11246. var diff = Math.abs(startAngle - endAngle);
  11247. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11248. // Is a circle
  11249. min$$1[0] = x - rx;
  11250. min$$1[1] = y - ry;
  11251. max$$1[0] = x + rx;
  11252. max$$1[1] = y + ry;
  11253. return;
  11254. }
  11255. start[0] = mathCos$2(startAngle) * rx + x;
  11256. start[1] = mathSin$2(startAngle) * ry + y;
  11257. end[0] = mathCos$2(endAngle) * rx + x;
  11258. end[1] = mathSin$2(endAngle) * ry + y;
  11259. vec2Min(min$$1, start, end);
  11260. vec2Max(max$$1, start, end);
  11261. // Thresh to [0, Math.PI * 2]
  11262. startAngle = startAngle % (PI2);
  11263. if (startAngle < 0) {
  11264. startAngle = startAngle + PI2;
  11265. }
  11266. endAngle = endAngle % (PI2);
  11267. if (endAngle < 0) {
  11268. endAngle = endAngle + PI2;
  11269. }
  11270. if (startAngle > endAngle && !anticlockwise) {
  11271. endAngle += PI2;
  11272. }
  11273. else if (startAngle < endAngle && anticlockwise) {
  11274. startAngle += PI2;
  11275. }
  11276. if (anticlockwise) {
  11277. var tmp = endAngle;
  11278. endAngle = startAngle;
  11279. startAngle = tmp;
  11280. }
  11281. // var number = 0;
  11282. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11283. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11284. if (angle > startAngle) {
  11285. extremity[0] = mathCos$2(angle) * rx + x;
  11286. extremity[1] = mathSin$2(angle) * ry + y;
  11287. vec2Min(min$$1, extremity, min$$1);
  11288. vec2Max(max$$1, extremity, max$$1);
  11289. }
  11290. }
  11291. }
  11292. /**
  11293. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11294. * 可以用于 isInsidePath 判断以及获取boundingRect
  11295. *
  11296. * @module zrender/core/PathProxy
  11297. * @author Yi Shen (http://www.github.com/pissang)
  11298. */
  11299. // TODO getTotalLength, getPointAtLength
  11300. var CMD = {
  11301. M: 1,
  11302. L: 2,
  11303. C: 3,
  11304. Q: 4,
  11305. A: 5,
  11306. Z: 6,
  11307. // Rect
  11308. R: 7
  11309. };
  11310. // var CMD_MEM_SIZE = {
  11311. // M: 3,
  11312. // L: 3,
  11313. // C: 7,
  11314. // Q: 5,
  11315. // A: 9,
  11316. // R: 5,
  11317. // Z: 1
  11318. // };
  11319. var min$1 = [];
  11320. var max$1 = [];
  11321. var min2 = [];
  11322. var max2 = [];
  11323. var mathMin$2 = Math.min;
  11324. var mathMax$2 = Math.max;
  11325. var mathCos$1 = Math.cos;
  11326. var mathSin$1 = Math.sin;
  11327. var mathSqrt$1 = Math.sqrt;
  11328. var mathAbs = Math.abs;
  11329. var hasTypedArray = typeof Float32Array !== 'undefined';
  11330. /**
  11331. * @alias module:zrender/core/PathProxy
  11332. * @constructor
  11333. */
  11334. var PathProxy = function (notSaveData) {
  11335. this._saveData = !(notSaveData || false);
  11336. if (this._saveData) {
  11337. /**
  11338. * Path data. Stored as flat array
  11339. * @type {Array.<Object>}
  11340. */
  11341. this.data = [];
  11342. }
  11343. this._ctx = null;
  11344. };
  11345. /**
  11346. * 快速计算Path包围盒(并不是最小包围盒)
  11347. * @return {Object}
  11348. */
  11349. PathProxy.prototype = {
  11350. constructor: PathProxy,
  11351. _xi: 0,
  11352. _yi: 0,
  11353. _x0: 0,
  11354. _y0: 0,
  11355. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11356. _ux: 0,
  11357. _uy: 0,
  11358. _len: 0,
  11359. _lineDash: null,
  11360. _dashOffset: 0,
  11361. _dashIdx: 0,
  11362. _dashSum: 0,
  11363. /**
  11364. * @readOnly
  11365. */
  11366. setScale: function (sx, sy) {
  11367. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  11368. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  11369. },
  11370. getContext: function () {
  11371. return this._ctx;
  11372. },
  11373. /**
  11374. * @param {CanvasRenderingContext2D} ctx
  11375. * @return {module:zrender/core/PathProxy}
  11376. */
  11377. beginPath: function (ctx) {
  11378. this._ctx = ctx;
  11379. ctx && ctx.beginPath();
  11380. ctx && (this.dpr = ctx.dpr);
  11381. // Reset
  11382. if (this._saveData) {
  11383. this._len = 0;
  11384. }
  11385. if (this._lineDash) {
  11386. this._lineDash = null;
  11387. this._dashOffset = 0;
  11388. }
  11389. return this;
  11390. },
  11391. /**
  11392. * @param {number} x
  11393. * @param {number} y
  11394. * @return {module:zrender/core/PathProxy}
  11395. */
  11396. moveTo: function (x, y) {
  11397. this.addData(CMD.M, x, y);
  11398. this._ctx && this._ctx.moveTo(x, y);
  11399. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11400. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11401. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11402. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11403. this._x0 = x;
  11404. this._y0 = y;
  11405. this._xi = x;
  11406. this._yi = y;
  11407. return this;
  11408. },
  11409. /**
  11410. * @param {number} x
  11411. * @param {number} y
  11412. * @return {module:zrender/core/PathProxy}
  11413. */
  11414. lineTo: function (x, y) {
  11415. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11416. || mathAbs(y - this._yi) > this._uy
  11417. // Force draw the first segment
  11418. || this._len < 5;
  11419. this.addData(CMD.L, x, y);
  11420. if (this._ctx && exceedUnit) {
  11421. this._needsDash() ? this._dashedLineTo(x, y)
  11422. : this._ctx.lineTo(x, y);
  11423. }
  11424. if (exceedUnit) {
  11425. this._xi = x;
  11426. this._yi = y;
  11427. }
  11428. return this;
  11429. },
  11430. /**
  11431. * @param {number} x1
  11432. * @param {number} y1
  11433. * @param {number} x2
  11434. * @param {number} y2
  11435. * @param {number} x3
  11436. * @param {number} y3
  11437. * @return {module:zrender/core/PathProxy}
  11438. */
  11439. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11440. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11441. if (this._ctx) {
  11442. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11443. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11444. }
  11445. this._xi = x3;
  11446. this._yi = y3;
  11447. return this;
  11448. },
  11449. /**
  11450. * @param {number} x1
  11451. * @param {number} y1
  11452. * @param {number} x2
  11453. * @param {number} y2
  11454. * @return {module:zrender/core/PathProxy}
  11455. */
  11456. quadraticCurveTo: function (x1, y1, x2, y2) {
  11457. this.addData(CMD.Q, x1, y1, x2, y2);
  11458. if (this._ctx) {
  11459. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11460. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11461. }
  11462. this._xi = x2;
  11463. this._yi = y2;
  11464. return this;
  11465. },
  11466. /**
  11467. * @param {number} cx
  11468. * @param {number} cy
  11469. * @param {number} r
  11470. * @param {number} startAngle
  11471. * @param {number} endAngle
  11472. * @param {boolean} anticlockwise
  11473. * @return {module:zrender/core/PathProxy}
  11474. */
  11475. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11476. this.addData(
  11477. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11478. );
  11479. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11480. this._xi = mathCos$1(endAngle) * r + cx;
  11481. this._yi = mathSin$1(endAngle) * r + cy;
  11482. return this;
  11483. },
  11484. // TODO
  11485. arcTo: function (x1, y1, x2, y2, radius) {
  11486. if (this._ctx) {
  11487. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11488. }
  11489. return this;
  11490. },
  11491. // TODO
  11492. rect: function (x, y, w, h) {
  11493. this._ctx && this._ctx.rect(x, y, w, h);
  11494. this.addData(CMD.R, x, y, w, h);
  11495. return this;
  11496. },
  11497. /**
  11498. * @return {module:zrender/core/PathProxy}
  11499. */
  11500. closePath: function () {
  11501. this.addData(CMD.Z);
  11502. var ctx = this._ctx;
  11503. var x0 = this._x0;
  11504. var y0 = this._y0;
  11505. if (ctx) {
  11506. this._needsDash() && this._dashedLineTo(x0, y0);
  11507. ctx.closePath();
  11508. }
  11509. this._xi = x0;
  11510. this._yi = y0;
  11511. return this;
  11512. },
  11513. /**
  11514. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11515. * stroke 同样
  11516. * @param {CanvasRenderingContext2D} ctx
  11517. * @return {module:zrender/core/PathProxy}
  11518. */
  11519. fill: function (ctx) {
  11520. ctx && ctx.fill();
  11521. this.toStatic();
  11522. },
  11523. /**
  11524. * @param {CanvasRenderingContext2D} ctx
  11525. * @return {module:zrender/core/PathProxy}
  11526. */
  11527. stroke: function (ctx) {
  11528. ctx && ctx.stroke();
  11529. this.toStatic();
  11530. },
  11531. /**
  11532. * 必须在其它绘制命令前调用
  11533. * Must be invoked before all other path drawing methods
  11534. * @return {module:zrender/core/PathProxy}
  11535. */
  11536. setLineDash: function (lineDash) {
  11537. if (lineDash instanceof Array) {
  11538. this._lineDash = lineDash;
  11539. this._dashIdx = 0;
  11540. var lineDashSum = 0;
  11541. for (var i = 0; i < lineDash.length; i++) {
  11542. lineDashSum += lineDash[i];
  11543. }
  11544. this._dashSum = lineDashSum;
  11545. }
  11546. return this;
  11547. },
  11548. /**
  11549. * 必须在其它绘制命令前调用
  11550. * Must be invoked before all other path drawing methods
  11551. * @return {module:zrender/core/PathProxy}
  11552. */
  11553. setLineDashOffset: function (offset) {
  11554. this._dashOffset = offset;
  11555. return this;
  11556. },
  11557. /**
  11558. *
  11559. * @return {boolean}
  11560. */
  11561. len: function () {
  11562. return this._len;
  11563. },
  11564. /**
  11565. * 直接设置 Path 数据
  11566. */
  11567. setData: function (data) {
  11568. var len$$1 = data.length;
  11569. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  11570. this.data = new Float32Array(len$$1);
  11571. }
  11572. for (var i = 0; i < len$$1; i++) {
  11573. this.data[i] = data[i];
  11574. }
  11575. this._len = len$$1;
  11576. },
  11577. /**
  11578. * 添加子路径
  11579. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11580. */
  11581. appendPath: function (path) {
  11582. if (!(path instanceof Array)) {
  11583. path = [path];
  11584. }
  11585. var len$$1 = path.length;
  11586. var appendSize = 0;
  11587. var offset = this._len;
  11588. for (var i = 0; i < len$$1; i++) {
  11589. appendSize += path[i].len();
  11590. }
  11591. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11592. this.data = new Float32Array(offset + appendSize);
  11593. }
  11594. for (var i = 0; i < len$$1; i++) {
  11595. var appendPathData = path[i].data;
  11596. for (var k = 0; k < appendPathData.length; k++) {
  11597. this.data[offset++] = appendPathData[k];
  11598. }
  11599. }
  11600. this._len = offset;
  11601. },
  11602. /**
  11603. * 填充 Path 数据。
  11604. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11605. */
  11606. addData: function (cmd) {
  11607. if (!this._saveData) {
  11608. return;
  11609. }
  11610. var data = this.data;
  11611. if (this._len + arguments.length > data.length) {
  11612. // 因为之前的数组已经转换成静态的 Float32Array
  11613. // 所以不够用时需要扩展一个新的动态数组
  11614. this._expandData();
  11615. data = this.data;
  11616. }
  11617. for (var i = 0; i < arguments.length; i++) {
  11618. data[this._len++] = arguments[i];
  11619. }
  11620. this._prevCmd = cmd;
  11621. },
  11622. _expandData: function () {
  11623. // Only if data is Float32Array
  11624. if (!(this.data instanceof Array)) {
  11625. var newData = [];
  11626. for (var i = 0; i < this._len; i++) {
  11627. newData[i] = this.data[i];
  11628. }
  11629. this.data = newData;
  11630. }
  11631. },
  11632. /**
  11633. * If needs js implemented dashed line
  11634. * @return {boolean}
  11635. * @private
  11636. */
  11637. _needsDash: function () {
  11638. return this._lineDash;
  11639. },
  11640. _dashedLineTo: function (x1, y1) {
  11641. var dashSum = this._dashSum;
  11642. var offset = this._dashOffset;
  11643. var lineDash = this._lineDash;
  11644. var ctx = this._ctx;
  11645. var x0 = this._xi;
  11646. var y0 = this._yi;
  11647. var dx = x1 - x0;
  11648. var dy = y1 - y0;
  11649. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11650. var x = x0;
  11651. var y = y0;
  11652. var dash;
  11653. var nDash = lineDash.length;
  11654. var idx;
  11655. dx /= dist$$1;
  11656. dy /= dist$$1;
  11657. if (offset < 0) {
  11658. // Convert to positive offset
  11659. offset = dashSum + offset;
  11660. }
  11661. offset %= dashSum;
  11662. x -= offset * dx;
  11663. y -= offset * dy;
  11664. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11665. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11666. idx = this._dashIdx;
  11667. dash = lineDash[idx];
  11668. x += dx * dash;
  11669. y += dy * dash;
  11670. this._dashIdx = (idx + 1) % nDash;
  11671. // Skip positive offset
  11672. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11673. continue;
  11674. }
  11675. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11676. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11677. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11678. );
  11679. }
  11680. // Offset for next lineTo
  11681. dx = x - x1;
  11682. dy = y - y1;
  11683. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11684. },
  11685. // Not accurate dashed line to
  11686. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11687. var dashSum = this._dashSum;
  11688. var offset = this._dashOffset;
  11689. var lineDash = this._lineDash;
  11690. var ctx = this._ctx;
  11691. var x0 = this._xi;
  11692. var y0 = this._yi;
  11693. var t;
  11694. var dx;
  11695. var dy;
  11696. var cubicAt$$1 = cubicAt;
  11697. var bezierLen = 0;
  11698. var idx = this._dashIdx;
  11699. var nDash = lineDash.length;
  11700. var x;
  11701. var y;
  11702. var tmpLen = 0;
  11703. if (offset < 0) {
  11704. // Convert to positive offset
  11705. offset = dashSum + offset;
  11706. }
  11707. offset %= dashSum;
  11708. // Bezier approx length
  11709. for (t = 0; t < 1; t += 0.1) {
  11710. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11711. - cubicAt$$1(x0, x1, x2, x3, t);
  11712. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11713. - cubicAt$$1(y0, y1, y2, y3, t);
  11714. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11715. }
  11716. // Find idx after add offset
  11717. for (; idx < nDash; idx++) {
  11718. tmpLen += lineDash[idx];
  11719. if (tmpLen > offset) {
  11720. break;
  11721. }
  11722. }
  11723. t = (tmpLen - offset) / bezierLen;
  11724. while (t <= 1) {
  11725. x = cubicAt$$1(x0, x1, x2, x3, t);
  11726. y = cubicAt$$1(y0, y1, y2, y3, t);
  11727. // Use line to approximate dashed bezier
  11728. // Bad result if dash is long
  11729. idx % 2 ? ctx.moveTo(x, y)
  11730. : ctx.lineTo(x, y);
  11731. t += lineDash[idx] / bezierLen;
  11732. idx = (idx + 1) % nDash;
  11733. }
  11734. // Finish the last segment and calculate the new offset
  11735. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11736. dx = x3 - x;
  11737. dy = y3 - y;
  11738. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11739. },
  11740. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11741. // Convert quadratic to cubic using degree elevation
  11742. var x3 = x2;
  11743. var y3 = y2;
  11744. x2 = (x2 + 2 * x1) / 3;
  11745. y2 = (y2 + 2 * y1) / 3;
  11746. x1 = (this._xi + 2 * x1) / 3;
  11747. y1 = (this._yi + 2 * y1) / 3;
  11748. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11749. },
  11750. /**
  11751. * 转成静态的 Float32Array 减少堆内存占用
  11752. * Convert dynamic array to static Float32Array
  11753. */
  11754. toStatic: function () {
  11755. var data = this.data;
  11756. if (data instanceof Array) {
  11757. data.length = this._len;
  11758. if (hasTypedArray) {
  11759. this.data = new Float32Array(data);
  11760. }
  11761. }
  11762. },
  11763. /**
  11764. * @return {module:zrender/core/BoundingRect}
  11765. */
  11766. getBoundingRect: function () {
  11767. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11768. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11769. var data = this.data;
  11770. var xi = 0;
  11771. var yi = 0;
  11772. var x0 = 0;
  11773. var y0 = 0;
  11774. for (var i = 0; i < data.length;) {
  11775. var cmd = data[i++];
  11776. if (i === 1) {
  11777. // 如果第一个命令是 L, C, Q
  11778. // 则 previous point 同绘制命令的第一个 point
  11779. //
  11780. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11781. xi = data[i];
  11782. yi = data[i + 1];
  11783. x0 = xi;
  11784. y0 = yi;
  11785. }
  11786. switch (cmd) {
  11787. case CMD.M:
  11788. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11789. // 在 closePath 的时候使用
  11790. x0 = data[i++];
  11791. y0 = data[i++];
  11792. xi = x0;
  11793. yi = y0;
  11794. min2[0] = x0;
  11795. min2[1] = y0;
  11796. max2[0] = x0;
  11797. max2[1] = y0;
  11798. break;
  11799. case CMD.L:
  11800. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11801. xi = data[i++];
  11802. yi = data[i++];
  11803. break;
  11804. case CMD.C:
  11805. fromCubic(
  11806. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11807. min2, max2
  11808. );
  11809. xi = data[i++];
  11810. yi = data[i++];
  11811. break;
  11812. case CMD.Q:
  11813. fromQuadratic(
  11814. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11815. min2, max2
  11816. );
  11817. xi = data[i++];
  11818. yi = data[i++];
  11819. break;
  11820. case CMD.A:
  11821. // TODO Arc 判断的开销比较大
  11822. var cx = data[i++];
  11823. var cy = data[i++];
  11824. var rx = data[i++];
  11825. var ry = data[i++];
  11826. var startAngle = data[i++];
  11827. var endAngle = data[i++] + startAngle;
  11828. // TODO Arc 旋转
  11829. i += 1;
  11830. var anticlockwise = 1 - data[i++];
  11831. if (i === 1) {
  11832. // 直接使用 arc 命令
  11833. // 第一个命令起点还未定义
  11834. x0 = mathCos$1(startAngle) * rx + cx;
  11835. y0 = mathSin$1(startAngle) * ry + cy;
  11836. }
  11837. fromArc(
  11838. cx, cy, rx, ry, startAngle, endAngle,
  11839. anticlockwise, min2, max2
  11840. );
  11841. xi = mathCos$1(endAngle) * rx + cx;
  11842. yi = mathSin$1(endAngle) * ry + cy;
  11843. break;
  11844. case CMD.R:
  11845. x0 = xi = data[i++];
  11846. y0 = yi = data[i++];
  11847. var width = data[i++];
  11848. var height = data[i++];
  11849. // Use fromLine
  11850. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11851. break;
  11852. case CMD.Z:
  11853. xi = x0;
  11854. yi = y0;
  11855. break;
  11856. }
  11857. // Union
  11858. min(min$1, min$1, min2);
  11859. max(max$1, max$1, max2);
  11860. }
  11861. // No data
  11862. if (i === 0) {
  11863. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11864. }
  11865. return new BoundingRect(
  11866. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11867. );
  11868. },
  11869. /**
  11870. * Rebuild path from current data
  11871. * Rebuild path will not consider javascript implemented line dash.
  11872. * @param {CanvasRenderingContext2D} ctx
  11873. */
  11874. rebuildPath: function (ctx) {
  11875. var d = this.data;
  11876. var x0, y0;
  11877. var xi, yi;
  11878. var x, y;
  11879. var ux = this._ux;
  11880. var uy = this._uy;
  11881. var len$$1 = this._len;
  11882. for (var i = 0; i < len$$1;) {
  11883. var cmd = d[i++];
  11884. if (i === 1) {
  11885. // 如果第一个命令是 L, C, Q
  11886. // 则 previous point 同绘制命令的第一个 point
  11887. //
  11888. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11889. xi = d[i];
  11890. yi = d[i + 1];
  11891. x0 = xi;
  11892. y0 = yi;
  11893. }
  11894. switch (cmd) {
  11895. case CMD.M:
  11896. x0 = xi = d[i++];
  11897. y0 = yi = d[i++];
  11898. ctx.moveTo(xi, yi);
  11899. break;
  11900. case CMD.L:
  11901. x = d[i++];
  11902. y = d[i++];
  11903. // Not draw too small seg between
  11904. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11905. ctx.lineTo(x, y);
  11906. xi = x;
  11907. yi = y;
  11908. }
  11909. break;
  11910. case CMD.C:
  11911. ctx.bezierCurveTo(
  11912. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11913. );
  11914. xi = d[i - 2];
  11915. yi = d[i - 1];
  11916. break;
  11917. case CMD.Q:
  11918. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11919. xi = d[i - 2];
  11920. yi = d[i - 1];
  11921. break;
  11922. case CMD.A:
  11923. var cx = d[i++];
  11924. var cy = d[i++];
  11925. var rx = d[i++];
  11926. var ry = d[i++];
  11927. var theta = d[i++];
  11928. var dTheta = d[i++];
  11929. var psi = d[i++];
  11930. var fs = d[i++];
  11931. var r = (rx > ry) ? rx : ry;
  11932. var scaleX = (rx > ry) ? 1 : rx / ry;
  11933. var scaleY = (rx > ry) ? ry / rx : 1;
  11934. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11935. var endAngle = theta + dTheta;
  11936. if (isEllipse) {
  11937. ctx.translate(cx, cy);
  11938. ctx.rotate(psi);
  11939. ctx.scale(scaleX, scaleY);
  11940. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11941. ctx.scale(1 / scaleX, 1 / scaleY);
  11942. ctx.rotate(-psi);
  11943. ctx.translate(-cx, -cy);
  11944. }
  11945. else {
  11946. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11947. }
  11948. if (i === 1) {
  11949. // 直接使用 arc 命令
  11950. // 第一个命令起点还未定义
  11951. x0 = mathCos$1(theta) * rx + cx;
  11952. y0 = mathSin$1(theta) * ry + cy;
  11953. }
  11954. xi = mathCos$1(endAngle) * rx + cx;
  11955. yi = mathSin$1(endAngle) * ry + cy;
  11956. break;
  11957. case CMD.R:
  11958. x0 = xi = d[i];
  11959. y0 = yi = d[i + 1];
  11960. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11961. break;
  11962. case CMD.Z:
  11963. ctx.closePath();
  11964. xi = x0;
  11965. yi = y0;
  11966. }
  11967. }
  11968. }
  11969. };
  11970. PathProxy.CMD = CMD;
  11971. /**
  11972. * 线段包含判断
  11973. * @param {number} x0
  11974. * @param {number} y0
  11975. * @param {number} x1
  11976. * @param {number} y1
  11977. * @param {number} lineWidth
  11978. * @param {number} x
  11979. * @param {number} y
  11980. * @return {boolean}
  11981. */
  11982. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11983. if (lineWidth === 0) {
  11984. return false;
  11985. }
  11986. var _l = lineWidth;
  11987. var _a = 0;
  11988. var _b = x0;
  11989. // Quick reject
  11990. if (
  11991. (y > y0 + _l && y > y1 + _l)
  11992. || (y < y0 - _l && y < y1 - _l)
  11993. || (x > x0 + _l && x > x1 + _l)
  11994. || (x < x0 - _l && x < x1 - _l)
  11995. ) {
  11996. return false;
  11997. }
  11998. if (x0 !== x1) {
  11999. _a = (y0 - y1) / (x0 - x1);
  12000. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  12001. }
  12002. else {
  12003. return Math.abs(x - x0) <= _l / 2;
  12004. }
  12005. var tmp = _a * x - y + _b;
  12006. var _s = tmp * tmp / (_a * _a + 1);
  12007. return _s <= _l / 2 * _l / 2;
  12008. }
  12009. /**
  12010. * 三次贝塞尔曲线描边包含判断
  12011. * @param {number} x0
  12012. * @param {number} y0
  12013. * @param {number} x1
  12014. * @param {number} y1
  12015. * @param {number} x2
  12016. * @param {number} y2
  12017. * @param {number} x3
  12018. * @param {number} y3
  12019. * @param {number} lineWidth
  12020. * @param {number} x
  12021. * @param {number} y
  12022. * @return {boolean}
  12023. */
  12024. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  12025. if (lineWidth === 0) {
  12026. return false;
  12027. }
  12028. var _l = lineWidth;
  12029. // Quick reject
  12030. if (
  12031. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  12032. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  12033. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  12034. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  12035. ) {
  12036. return false;
  12037. }
  12038. var d = cubicProjectPoint(
  12039. x0, y0, x1, y1, x2, y2, x3, y3,
  12040. x, y, null
  12041. );
  12042. return d <= _l / 2;
  12043. }
  12044. /**
  12045. * 二次贝塞尔曲线描边包含判断
  12046. * @param {number} x0
  12047. * @param {number} y0
  12048. * @param {number} x1
  12049. * @param {number} y1
  12050. * @param {number} x2
  12051. * @param {number} y2
  12052. * @param {number} lineWidth
  12053. * @param {number} x
  12054. * @param {number} y
  12055. * @return {boolean}
  12056. */
  12057. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  12058. if (lineWidth === 0) {
  12059. return false;
  12060. }
  12061. var _l = lineWidth;
  12062. // Quick reject
  12063. if (
  12064. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  12065. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  12066. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  12067. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  12068. ) {
  12069. return false;
  12070. }
  12071. var d = quadraticProjectPoint(
  12072. x0, y0, x1, y1, x2, y2,
  12073. x, y, null
  12074. );
  12075. return d <= _l / 2;
  12076. }
  12077. var PI2$3 = Math.PI * 2;
  12078. function normalizeRadian(angle) {
  12079. angle %= PI2$3;
  12080. if (angle < 0) {
  12081. angle += PI2$3;
  12082. }
  12083. return angle;
  12084. }
  12085. var PI2$2 = Math.PI * 2;
  12086. /**
  12087. * 圆弧描边包含判断
  12088. * @param {number} cx
  12089. * @param {number} cy
  12090. * @param {number} r
  12091. * @param {number} startAngle
  12092. * @param {number} endAngle
  12093. * @param {boolean} anticlockwise
  12094. * @param {number} lineWidth
  12095. * @param {number} x
  12096. * @param {number} y
  12097. * @return {Boolean}
  12098. */
  12099. function containStroke$4(
  12100. cx, cy, r, startAngle, endAngle, anticlockwise,
  12101. lineWidth, x, y
  12102. ) {
  12103. if (lineWidth === 0) {
  12104. return false;
  12105. }
  12106. var _l = lineWidth;
  12107. x -= cx;
  12108. y -= cy;
  12109. var d = Math.sqrt(x * x + y * y);
  12110. if ((d - _l > r) || (d + _l < r)) {
  12111. return false;
  12112. }
  12113. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12114. // Is a circle
  12115. return true;
  12116. }
  12117. if (anticlockwise) {
  12118. var tmp = startAngle;
  12119. startAngle = normalizeRadian(endAngle);
  12120. endAngle = normalizeRadian(tmp);
  12121. }
  12122. else {
  12123. startAngle = normalizeRadian(startAngle);
  12124. endAngle = normalizeRadian(endAngle);
  12125. }
  12126. if (startAngle > endAngle) {
  12127. endAngle += PI2$2;
  12128. }
  12129. var angle = Math.atan2(y, x);
  12130. if (angle < 0) {
  12131. angle += PI2$2;
  12132. }
  12133. return (angle >= startAngle && angle <= endAngle)
  12134. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12135. }
  12136. function windingLine(x0, y0, x1, y1, x, y) {
  12137. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12138. return 0;
  12139. }
  12140. // Ignore horizontal line
  12141. if (y1 === y0) {
  12142. return 0;
  12143. }
  12144. var dir = y1 < y0 ? 1 : -1;
  12145. var t = (y - y0) / (y1 - y0);
  12146. // Avoid winding error when intersection point is the connect point of two line of polygon
  12147. if (t === 1 || t === 0) {
  12148. dir = y1 < y0 ? 0.5 : -0.5;
  12149. }
  12150. var x_ = t * (x1 - x0) + x0;
  12151. // If (x, y) on the line, considered as "contain".
  12152. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12153. }
  12154. var CMD$1 = PathProxy.CMD;
  12155. var PI2$1 = Math.PI * 2;
  12156. var EPSILON$2 = 1e-4;
  12157. function isAroundEqual(a, b) {
  12158. return Math.abs(a - b) < EPSILON$2;
  12159. }
  12160. // 临时数组
  12161. var roots = [-1, -1, -1];
  12162. var extrema = [-1, -1];
  12163. function swapExtrema() {
  12164. var tmp = extrema[0];
  12165. extrema[0] = extrema[1];
  12166. extrema[1] = tmp;
  12167. }
  12168. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12169. // Quick reject
  12170. if (
  12171. (y > y0 && y > y1 && y > y2 && y > y3)
  12172. || (y < y0 && y < y1 && y < y2 && y < y3)
  12173. ) {
  12174. return 0;
  12175. }
  12176. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12177. if (nRoots === 0) {
  12178. return 0;
  12179. }
  12180. else {
  12181. var w = 0;
  12182. var nExtrema = -1;
  12183. var y0_;
  12184. var y1_;
  12185. for (var i = 0; i < nRoots; i++) {
  12186. var t = roots[i];
  12187. // Avoid winding error when intersection point is the connect point of two line of polygon
  12188. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12189. var x_ = cubicAt(x0, x1, x2, x3, t);
  12190. if (x_ < x) { // Quick reject
  12191. continue;
  12192. }
  12193. if (nExtrema < 0) {
  12194. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12195. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12196. swapExtrema();
  12197. }
  12198. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12199. if (nExtrema > 1) {
  12200. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12201. }
  12202. }
  12203. if (nExtrema === 2) {
  12204. // 分成三段单调函数
  12205. if (t < extrema[0]) {
  12206. w += y0_ < y0 ? unit : -unit;
  12207. }
  12208. else if (t < extrema[1]) {
  12209. w += y1_ < y0_ ? unit : -unit;
  12210. }
  12211. else {
  12212. w += y3 < y1_ ? unit : -unit;
  12213. }
  12214. }
  12215. else {
  12216. // 分成两段单调函数
  12217. if (t < extrema[0]) {
  12218. w += y0_ < y0 ? unit : -unit;
  12219. }
  12220. else {
  12221. w += y3 < y0_ ? unit : -unit;
  12222. }
  12223. }
  12224. }
  12225. return w;
  12226. }
  12227. }
  12228. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12229. // Quick reject
  12230. if (
  12231. (y > y0 && y > y1 && y > y2)
  12232. || (y < y0 && y < y1 && y < y2)
  12233. ) {
  12234. return 0;
  12235. }
  12236. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12237. if (nRoots === 0) {
  12238. return 0;
  12239. }
  12240. else {
  12241. var t = quadraticExtremum(y0, y1, y2);
  12242. if (t >= 0 && t <= 1) {
  12243. var w = 0;
  12244. var y_ = quadraticAt(y0, y1, y2, t);
  12245. for (var i = 0; i < nRoots; i++) {
  12246. // Remove one endpoint.
  12247. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12248. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12249. if (x_ < x) { // Quick reject
  12250. continue;
  12251. }
  12252. if (roots[i] < t) {
  12253. w += y_ < y0 ? unit : -unit;
  12254. }
  12255. else {
  12256. w += y2 < y_ ? unit : -unit;
  12257. }
  12258. }
  12259. return w;
  12260. }
  12261. else {
  12262. // Remove one endpoint.
  12263. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12264. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12265. if (x_ < x) { // Quick reject
  12266. return 0;
  12267. }
  12268. return y2 < y0 ? unit : -unit;
  12269. }
  12270. }
  12271. }
  12272. // TODO
  12273. // Arc 旋转
  12274. function windingArc(
  12275. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12276. ) {
  12277. y -= cy;
  12278. if (y > r || y < -r) {
  12279. return 0;
  12280. }
  12281. var tmp = Math.sqrt(r * r - y * y);
  12282. roots[0] = -tmp;
  12283. roots[1] = tmp;
  12284. var diff = Math.abs(startAngle - endAngle);
  12285. if (diff < 1e-4) {
  12286. return 0;
  12287. }
  12288. if (diff % PI2$1 < 1e-4) {
  12289. // Is a circle
  12290. startAngle = 0;
  12291. endAngle = PI2$1;
  12292. var dir = anticlockwise ? 1 : -1;
  12293. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12294. return dir;
  12295. }
  12296. else {
  12297. return 0;
  12298. }
  12299. }
  12300. if (anticlockwise) {
  12301. var tmp = startAngle;
  12302. startAngle = normalizeRadian(endAngle);
  12303. endAngle = normalizeRadian(tmp);
  12304. }
  12305. else {
  12306. startAngle = normalizeRadian(startAngle);
  12307. endAngle = normalizeRadian(endAngle);
  12308. }
  12309. if (startAngle > endAngle) {
  12310. endAngle += PI2$1;
  12311. }
  12312. var w = 0;
  12313. for (var i = 0; i < 2; i++) {
  12314. var x_ = roots[i];
  12315. if (x_ + cx > x) {
  12316. var angle = Math.atan2(y, x_);
  12317. var dir = anticlockwise ? 1 : -1;
  12318. if (angle < 0) {
  12319. angle = PI2$1 + angle;
  12320. }
  12321. if (
  12322. (angle >= startAngle && angle <= endAngle)
  12323. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12324. ) {
  12325. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12326. dir = -dir;
  12327. }
  12328. w += dir;
  12329. }
  12330. }
  12331. }
  12332. return w;
  12333. }
  12334. function containPath(data, lineWidth, isStroke, x, y) {
  12335. var w = 0;
  12336. var xi = 0;
  12337. var yi = 0;
  12338. var x0 = 0;
  12339. var y0 = 0;
  12340. for (var i = 0; i < data.length;) {
  12341. var cmd = data[i++];
  12342. // Begin a new subpath
  12343. if (cmd === CMD$1.M && i > 1) {
  12344. // Close previous subpath
  12345. if (!isStroke) {
  12346. w += windingLine(xi, yi, x0, y0, x, y);
  12347. }
  12348. // 如果被任何一个 subpath 包含
  12349. // if (w !== 0) {
  12350. // return true;
  12351. // }
  12352. }
  12353. if (i === 1) {
  12354. // 如果第一个命令是 L, C, Q
  12355. // 则 previous point 同绘制命令的第一个 point
  12356. //
  12357. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12358. xi = data[i];
  12359. yi = data[i + 1];
  12360. x0 = xi;
  12361. y0 = yi;
  12362. }
  12363. switch (cmd) {
  12364. case CMD$1.M:
  12365. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12366. // 在 closePath 的时候使用
  12367. x0 = data[i++];
  12368. y0 = data[i++];
  12369. xi = x0;
  12370. yi = y0;
  12371. break;
  12372. case CMD$1.L:
  12373. if (isStroke) {
  12374. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12375. return true;
  12376. }
  12377. }
  12378. else {
  12379. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12380. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12381. }
  12382. xi = data[i++];
  12383. yi = data[i++];
  12384. break;
  12385. case CMD$1.C:
  12386. if (isStroke) {
  12387. if (containStroke$2(xi, yi,
  12388. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12389. lineWidth, x, y
  12390. )) {
  12391. return true;
  12392. }
  12393. }
  12394. else {
  12395. w += windingCubic(
  12396. xi, yi,
  12397. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12398. x, y
  12399. ) || 0;
  12400. }
  12401. xi = data[i++];
  12402. yi = data[i++];
  12403. break;
  12404. case CMD$1.Q:
  12405. if (isStroke) {
  12406. if (containStroke$3(xi, yi,
  12407. data[i++], data[i++], data[i], data[i + 1],
  12408. lineWidth, x, y
  12409. )) {
  12410. return true;
  12411. }
  12412. }
  12413. else {
  12414. w += windingQuadratic(
  12415. xi, yi,
  12416. data[i++], data[i++], data[i], data[i + 1],
  12417. x, y
  12418. ) || 0;
  12419. }
  12420. xi = data[i++];
  12421. yi = data[i++];
  12422. break;
  12423. case CMD$1.A:
  12424. // TODO Arc 判断的开销比较大
  12425. var cx = data[i++];
  12426. var cy = data[i++];
  12427. var rx = data[i++];
  12428. var ry = data[i++];
  12429. var theta = data[i++];
  12430. var dTheta = data[i++];
  12431. // TODO Arc 旋转
  12432. i += 1;
  12433. var anticlockwise = 1 - data[i++];
  12434. var x1 = Math.cos(theta) * rx + cx;
  12435. var y1 = Math.sin(theta) * ry + cy;
  12436. // 不是直接使用 arc 命令
  12437. if (i > 1) {
  12438. w += windingLine(xi, yi, x1, y1, x, y);
  12439. }
  12440. else {
  12441. // 第一个命令起点还未定义
  12442. x0 = x1;
  12443. y0 = y1;
  12444. }
  12445. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12446. var _x = (x - cx) * ry / rx + cx;
  12447. if (isStroke) {
  12448. if (containStroke$4(
  12449. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12450. lineWidth, _x, y
  12451. )) {
  12452. return true;
  12453. }
  12454. }
  12455. else {
  12456. w += windingArc(
  12457. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12458. _x, y
  12459. );
  12460. }
  12461. xi = Math.cos(theta + dTheta) * rx + cx;
  12462. yi = Math.sin(theta + dTheta) * ry + cy;
  12463. break;
  12464. case CMD$1.R:
  12465. x0 = xi = data[i++];
  12466. y0 = yi = data[i++];
  12467. var width = data[i++];
  12468. var height = data[i++];
  12469. var x1 = x0 + width;
  12470. var y1 = y0 + height;
  12471. if (isStroke) {
  12472. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12473. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12474. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12475. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12476. ) {
  12477. return true;
  12478. }
  12479. }
  12480. else {
  12481. // FIXME Clockwise ?
  12482. w += windingLine(x1, y0, x1, y1, x, y);
  12483. w += windingLine(x0, y1, x0, y0, x, y);
  12484. }
  12485. break;
  12486. case CMD$1.Z:
  12487. if (isStroke) {
  12488. if (containStroke$1(
  12489. xi, yi, x0, y0, lineWidth, x, y
  12490. )) {
  12491. return true;
  12492. }
  12493. }
  12494. else {
  12495. // Close a subpath
  12496. w += windingLine(xi, yi, x0, y0, x, y);
  12497. // 如果被任何一个 subpath 包含
  12498. // FIXME subpaths may overlap
  12499. // if (w !== 0) {
  12500. // return true;
  12501. // }
  12502. }
  12503. xi = x0;
  12504. yi = y0;
  12505. break;
  12506. }
  12507. }
  12508. if (!isStroke && !isAroundEqual(yi, y0)) {
  12509. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12510. }
  12511. return w !== 0;
  12512. }
  12513. function contain(pathData, x, y) {
  12514. return containPath(pathData, 0, false, x, y);
  12515. }
  12516. function containStroke(pathData, lineWidth, x, y) {
  12517. return containPath(pathData, lineWidth, true, x, y);
  12518. }
  12519. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12520. var abs = Math.abs;
  12521. var pathProxyForDraw = new PathProxy(true);
  12522. /**
  12523. * @alias module:zrender/graphic/Path
  12524. * @extends module:zrender/graphic/Displayable
  12525. * @constructor
  12526. * @param {Object} opts
  12527. */
  12528. function Path(opts) {
  12529. Displayable.call(this, opts);
  12530. /**
  12531. * @type {module:zrender/core/PathProxy}
  12532. * @readOnly
  12533. */
  12534. this.path = null;
  12535. }
  12536. Path.prototype = {
  12537. constructor: Path,
  12538. type: 'path',
  12539. __dirtyPath: true,
  12540. strokeContainThreshold: 5,
  12541. /**
  12542. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  12543. * @type {boolean}
  12544. */
  12545. subPixelOptimize: false,
  12546. brush: function (ctx, prevEl) {
  12547. var style = this.style;
  12548. var path = this.path || pathProxyForDraw;
  12549. var hasStroke = style.hasStroke();
  12550. var hasFill = style.hasFill();
  12551. var fill = style.fill;
  12552. var stroke = style.stroke;
  12553. var hasFillGradient = hasFill && !!(fill.colorStops);
  12554. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12555. var hasFillPattern = hasFill && !!(fill.image);
  12556. var hasStrokePattern = hasStroke && !!(stroke.image);
  12557. style.bind(ctx, this, prevEl);
  12558. this.setTransform(ctx);
  12559. if (this.__dirty) {
  12560. var rect;
  12561. // Update gradient because bounding rect may changed
  12562. if (hasFillGradient) {
  12563. rect = rect || this.getBoundingRect();
  12564. this._fillGradient = style.getGradient(ctx, fill, rect);
  12565. }
  12566. if (hasStrokeGradient) {
  12567. rect = rect || this.getBoundingRect();
  12568. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12569. }
  12570. }
  12571. // Use the gradient or pattern
  12572. if (hasFillGradient) {
  12573. // PENDING If may have affect the state
  12574. ctx.fillStyle = this._fillGradient;
  12575. }
  12576. else if (hasFillPattern) {
  12577. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12578. }
  12579. if (hasStrokeGradient) {
  12580. ctx.strokeStyle = this._strokeGradient;
  12581. }
  12582. else if (hasStrokePattern) {
  12583. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12584. }
  12585. var lineDash = style.lineDash;
  12586. var lineDashOffset = style.lineDashOffset;
  12587. var ctxLineDash = !!ctx.setLineDash;
  12588. // Update path sx, sy
  12589. var scale = this.getGlobalScale();
  12590. path.setScale(scale[0], scale[1]);
  12591. // Proxy context
  12592. // Rebuild path in following 2 cases
  12593. // 1. Path is dirty
  12594. // 2. Path needs javascript implemented lineDash stroking.
  12595. // In this case, lineDash information will not be saved in PathProxy
  12596. if (this.__dirtyPath
  12597. || (lineDash && !ctxLineDash && hasStroke)
  12598. ) {
  12599. path.beginPath(ctx);
  12600. // Setting line dash before build path
  12601. if (lineDash && !ctxLineDash) {
  12602. path.setLineDash(lineDash);
  12603. path.setLineDashOffset(lineDashOffset);
  12604. }
  12605. this.buildPath(path, this.shape, false);
  12606. // Clear path dirty flag
  12607. if (this.path) {
  12608. this.__dirtyPath = false;
  12609. }
  12610. }
  12611. else {
  12612. // Replay path building
  12613. ctx.beginPath();
  12614. this.path.rebuildPath(ctx);
  12615. }
  12616. if (hasFill) {
  12617. if (style.fillOpacity != null) {
  12618. var originalGlobalAlpha = ctx.globalAlpha;
  12619. ctx.globalAlpha = style.fillOpacity * style.opacity;
  12620. path.fill(ctx);
  12621. ctx.globalAlpha = originalGlobalAlpha;
  12622. }
  12623. else {
  12624. path.fill(ctx);
  12625. }
  12626. }
  12627. if (lineDash && ctxLineDash) {
  12628. ctx.setLineDash(lineDash);
  12629. ctx.lineDashOffset = lineDashOffset;
  12630. }
  12631. if (hasStroke) {
  12632. if (style.strokeOpacity != null) {
  12633. var originalGlobalAlpha = ctx.globalAlpha;
  12634. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  12635. path.stroke(ctx);
  12636. ctx.globalAlpha = originalGlobalAlpha;
  12637. }
  12638. else {
  12639. path.stroke(ctx);
  12640. }
  12641. }
  12642. if (lineDash && ctxLineDash) {
  12643. // PENDING
  12644. // Remove lineDash
  12645. ctx.setLineDash([]);
  12646. }
  12647. // Draw rect text
  12648. if (style.text != null) {
  12649. // Only restore transform when needs draw text.
  12650. this.restoreTransform(ctx);
  12651. this.drawRectText(ctx, this.getBoundingRect());
  12652. }
  12653. },
  12654. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12655. // Like in circle
  12656. buildPath: function (ctx, shapeCfg, inBundle) {},
  12657. createPathProxy: function () {
  12658. this.path = new PathProxy();
  12659. },
  12660. getBoundingRect: function () {
  12661. var rect = this._rect;
  12662. var style = this.style;
  12663. var needsUpdateRect = !rect;
  12664. if (needsUpdateRect) {
  12665. var path = this.path;
  12666. if (!path) {
  12667. // Create path on demand.
  12668. path = this.path = new PathProxy();
  12669. }
  12670. if (this.__dirtyPath) {
  12671. path.beginPath();
  12672. this.buildPath(path, this.shape, false);
  12673. }
  12674. rect = path.getBoundingRect();
  12675. }
  12676. this._rect = rect;
  12677. if (style.hasStroke()) {
  12678. // Needs update rect with stroke lineWidth when
  12679. // 1. Element changes scale or lineWidth
  12680. // 2. Shape is changed
  12681. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12682. if (this.__dirty || needsUpdateRect) {
  12683. rectWithStroke.copy(rect);
  12684. // FIXME Must after updateTransform
  12685. var w = style.lineWidth;
  12686. // PENDING, Min line width is needed when line is horizontal or vertical
  12687. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12688. // Only add extra hover lineWidth when there are no fill
  12689. if (!style.hasFill()) {
  12690. w = Math.max(w, this.strokeContainThreshold || 4);
  12691. }
  12692. // Consider line width
  12693. // Line scale can't be 0;
  12694. if (lineScale > 1e-10) {
  12695. rectWithStroke.width += w / lineScale;
  12696. rectWithStroke.height += w / lineScale;
  12697. rectWithStroke.x -= w / lineScale / 2;
  12698. rectWithStroke.y -= w / lineScale / 2;
  12699. }
  12700. }
  12701. // Return rect with stroke
  12702. return rectWithStroke;
  12703. }
  12704. return rect;
  12705. },
  12706. contain: function (x, y) {
  12707. var localPos = this.transformCoordToLocal(x, y);
  12708. var rect = this.getBoundingRect();
  12709. var style = this.style;
  12710. x = localPos[0];
  12711. y = localPos[1];
  12712. if (rect.contain(x, y)) {
  12713. var pathData = this.path.data;
  12714. if (style.hasStroke()) {
  12715. var lineWidth = style.lineWidth;
  12716. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12717. // Line scale can't be 0;
  12718. if (lineScale > 1e-10) {
  12719. // Only add extra hover lineWidth when there are no fill
  12720. if (!style.hasFill()) {
  12721. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12722. }
  12723. if (containStroke(
  12724. pathData, lineWidth / lineScale, x, y
  12725. )) {
  12726. return true;
  12727. }
  12728. }
  12729. }
  12730. if (style.hasFill()) {
  12731. return contain(pathData, x, y);
  12732. }
  12733. }
  12734. return false;
  12735. },
  12736. /**
  12737. * @param {boolean} dirtyPath
  12738. */
  12739. dirty: function (dirtyPath) {
  12740. if (dirtyPath == null) {
  12741. dirtyPath = true;
  12742. }
  12743. // Only mark dirty, not mark clean
  12744. if (dirtyPath) {
  12745. this.__dirtyPath = dirtyPath;
  12746. this._rect = null;
  12747. }
  12748. this.__dirty = this.__dirtyText = true;
  12749. this.__zr && this.__zr.refresh();
  12750. // Used as a clipping path
  12751. if (this.__clipTarget) {
  12752. this.__clipTarget.dirty();
  12753. }
  12754. },
  12755. /**
  12756. * Alias for animate('shape')
  12757. * @param {boolean} loop
  12758. */
  12759. animateShape: function (loop) {
  12760. return this.animate('shape', loop);
  12761. },
  12762. // Overwrite attrKV
  12763. attrKV: function (key, value) {
  12764. // FIXME
  12765. if (key === 'shape') {
  12766. this.setShape(value);
  12767. this.__dirtyPath = true;
  12768. this._rect = null;
  12769. }
  12770. else {
  12771. Displayable.prototype.attrKV.call(this, key, value);
  12772. }
  12773. },
  12774. /**
  12775. * @param {Object|string} key
  12776. * @param {*} value
  12777. */
  12778. setShape: function (key, value) {
  12779. var shape = this.shape;
  12780. // Path from string may not have shape
  12781. if (shape) {
  12782. if (isObject$1(key)) {
  12783. for (var name in key) {
  12784. if (key.hasOwnProperty(name)) {
  12785. shape[name] = key[name];
  12786. }
  12787. }
  12788. }
  12789. else {
  12790. shape[key] = value;
  12791. }
  12792. this.dirty(true);
  12793. }
  12794. return this;
  12795. },
  12796. getLineScale: function () {
  12797. var m = this.transform;
  12798. // Get the line scale.
  12799. // Determinant of `m` means how much the area is enlarged by the
  12800. // transformation. So its square root can be used as a scale factor
  12801. // for width.
  12802. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12803. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12804. : 1;
  12805. }
  12806. };
  12807. /**
  12808. * 扩展一个 Path element, 比如星形,圆等。
  12809. * Extend a path element
  12810. * @param {Object} props
  12811. * @param {string} props.type Path type
  12812. * @param {Function} props.init Initialize
  12813. * @param {Function} props.buildPath Overwrite buildPath method
  12814. * @param {Object} [props.style] Extended default style config
  12815. * @param {Object} [props.shape] Extended default shape config
  12816. */
  12817. Path.extend = function (defaults$$1) {
  12818. var Sub = function (opts) {
  12819. Path.call(this, opts);
  12820. if (defaults$$1.style) {
  12821. // Extend default style
  12822. this.style.extendFrom(defaults$$1.style, false);
  12823. }
  12824. // Extend default shape
  12825. var defaultShape = defaults$$1.shape;
  12826. if (defaultShape) {
  12827. this.shape = this.shape || {};
  12828. var thisShape = this.shape;
  12829. for (var name in defaultShape) {
  12830. if (
  12831. !thisShape.hasOwnProperty(name)
  12832. && defaultShape.hasOwnProperty(name)
  12833. ) {
  12834. thisShape[name] = defaultShape[name];
  12835. }
  12836. }
  12837. }
  12838. defaults$$1.init && defaults$$1.init.call(this, opts);
  12839. };
  12840. inherits(Sub, Path);
  12841. // FIXME 不能 extend position, rotation 等引用对象
  12842. for (var name in defaults$$1) {
  12843. // Extending prototype values and methods
  12844. if (name !== 'style' && name !== 'shape') {
  12845. Sub.prototype[name] = defaults$$1[name];
  12846. }
  12847. }
  12848. return Sub;
  12849. };
  12850. inherits(Path, Displayable);
  12851. var CMD$2 = PathProxy.CMD;
  12852. var points = [[], [], []];
  12853. var mathSqrt$3 = Math.sqrt;
  12854. var mathAtan2 = Math.atan2;
  12855. var transformPath = function (path, m) {
  12856. var data = path.data;
  12857. var cmd;
  12858. var nPoint;
  12859. var i;
  12860. var j;
  12861. var k;
  12862. var p;
  12863. var M = CMD$2.M;
  12864. var C = CMD$2.C;
  12865. var L = CMD$2.L;
  12866. var R = CMD$2.R;
  12867. var A = CMD$2.A;
  12868. var Q = CMD$2.Q;
  12869. for (i = 0, j = 0; i < data.length;) {
  12870. cmd = data[i++];
  12871. j = i;
  12872. nPoint = 0;
  12873. switch (cmd) {
  12874. case M:
  12875. nPoint = 1;
  12876. break;
  12877. case L:
  12878. nPoint = 1;
  12879. break;
  12880. case C:
  12881. nPoint = 3;
  12882. break;
  12883. case Q:
  12884. nPoint = 2;
  12885. break;
  12886. case A:
  12887. var x = m[4];
  12888. var y = m[5];
  12889. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12890. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12891. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12892. // cx
  12893. data[i] *= sx;
  12894. data[i++] += x;
  12895. // cy
  12896. data[i] *= sy;
  12897. data[i++] += y;
  12898. // Scale rx and ry
  12899. // FIXME Assume psi is 0 here
  12900. data[i++] *= sx;
  12901. data[i++] *= sy;
  12902. // Start angle
  12903. data[i++] += angle;
  12904. // end angle
  12905. data[i++] += angle;
  12906. // FIXME psi
  12907. i += 2;
  12908. j = i;
  12909. break;
  12910. case R:
  12911. // x0, y0
  12912. p[0] = data[i++];
  12913. p[1] = data[i++];
  12914. applyTransform(p, p, m);
  12915. data[j++] = p[0];
  12916. data[j++] = p[1];
  12917. // x1, y1
  12918. p[0] += data[i++];
  12919. p[1] += data[i++];
  12920. applyTransform(p, p, m);
  12921. data[j++] = p[0];
  12922. data[j++] = p[1];
  12923. }
  12924. for (k = 0; k < nPoint; k++) {
  12925. var p = points[k];
  12926. p[0] = data[i++];
  12927. p[1] = data[i++];
  12928. applyTransform(p, p, m);
  12929. // Write back
  12930. data[j++] = p[0];
  12931. data[j++] = p[1];
  12932. }
  12933. }
  12934. };
  12935. // command chars
  12936. // var cc = [
  12937. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12938. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12939. // ];
  12940. var mathSqrt = Math.sqrt;
  12941. var mathSin = Math.sin;
  12942. var mathCos = Math.cos;
  12943. var PI = Math.PI;
  12944. var vMag = function (v) {
  12945. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12946. };
  12947. var vRatio = function (u, v) {
  12948. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12949. };
  12950. var vAngle = function (u, v) {
  12951. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12952. * Math.acos(vRatio(u, v));
  12953. };
  12954. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12955. var psi = psiDeg * (PI / 180.0);
  12956. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12957. + mathSin(psi) * (y1 - y2) / 2.0;
  12958. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12959. + mathCos(psi) * (y1 - y2) / 2.0;
  12960. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12961. if (lambda > 1) {
  12962. rx *= mathSqrt(lambda);
  12963. ry *= mathSqrt(lambda);
  12964. }
  12965. var f = (fa === fs ? -1 : 1)
  12966. * mathSqrt((((rx * rx) * (ry * ry))
  12967. - ((rx * rx) * (yp * yp))
  12968. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12969. + (ry * ry) * (xp * xp))
  12970. ) || 0;
  12971. var cxp = f * rx * yp / ry;
  12972. var cyp = f * -ry * xp / rx;
  12973. var cx = (x1 + x2) / 2.0
  12974. + mathCos(psi) * cxp
  12975. - mathSin(psi) * cyp;
  12976. var cy = (y1 + y2) / 2.0
  12977. + mathSin(psi) * cxp
  12978. + mathCos(psi) * cyp;
  12979. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12980. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12981. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12982. var dTheta = vAngle(u, v);
  12983. if (vRatio(u, v) <= -1) {
  12984. dTheta = PI;
  12985. }
  12986. if (vRatio(u, v) >= 1) {
  12987. dTheta = 0;
  12988. }
  12989. if (fs === 0 && dTheta > 0) {
  12990. dTheta = dTheta - 2 * PI;
  12991. }
  12992. if (fs === 1 && dTheta < 0) {
  12993. dTheta = dTheta + 2 * PI;
  12994. }
  12995. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12996. }
  12997. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12998. // Consider case:
  12999. // (1) delimiter can be comma or space, where continuous commas
  13000. // or spaces should be seen as one comma.
  13001. // (2) value can be like:
  13002. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  13003. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  13004. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  13005. // var valueSplitReg = /[\s,]+/;
  13006. function createPathProxyFromString(data) {
  13007. if (!data) {
  13008. return new PathProxy();
  13009. }
  13010. // var data = data.replace(/-/g, ' -')
  13011. // .replace(/ /g, ' ')
  13012. // .replace(/ /g, ',')
  13013. // .replace(/,,/g, ',');
  13014. // var n;
  13015. // create pipes so that we can split the data
  13016. // for (n = 0; n < cc.length; n++) {
  13017. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  13018. // }
  13019. // data = data.replace(/-/g, ',-');
  13020. // create array
  13021. // var arr = cs.split('|');
  13022. // init context point
  13023. var cpx = 0;
  13024. var cpy = 0;
  13025. var subpathX = cpx;
  13026. var subpathY = cpy;
  13027. var prevCmd;
  13028. var path = new PathProxy();
  13029. var CMD = PathProxy.CMD;
  13030. // commandReg.lastIndex = 0;
  13031. // var cmdResult;
  13032. // while ((cmdResult = commandReg.exec(data)) != null) {
  13033. // var cmdStr = cmdResult[1];
  13034. // var cmdContent = cmdResult[2];
  13035. var cmdList = data.match(commandReg);
  13036. for (var l = 0; l < cmdList.length; l++) {
  13037. var cmdText = cmdList[l];
  13038. var cmdStr = cmdText.charAt(0);
  13039. var cmd;
  13040. // String#split is faster a little bit than String#replace or RegExp#exec.
  13041. // var p = cmdContent.split(valueSplitReg);
  13042. // var pLen = 0;
  13043. // for (var i = 0; i < p.length; i++) {
  13044. // // '' and other invalid str => NaN
  13045. // var val = parseFloat(p[i]);
  13046. // !isNaN(val) && (p[pLen++] = val);
  13047. // }
  13048. var p = cmdText.match(numberReg) || [];
  13049. var pLen = p.length;
  13050. for (var i = 0; i < pLen; i++) {
  13051. p[i] = parseFloat(p[i]);
  13052. }
  13053. var off = 0;
  13054. while (off < pLen) {
  13055. var ctlPtx;
  13056. var ctlPty;
  13057. var rx;
  13058. var ry;
  13059. var psi;
  13060. var fa;
  13061. var fs;
  13062. var x1 = cpx;
  13063. var y1 = cpy;
  13064. // convert l, H, h, V, and v to L
  13065. switch (cmdStr) {
  13066. case 'l':
  13067. cpx += p[off++];
  13068. cpy += p[off++];
  13069. cmd = CMD.L;
  13070. path.addData(cmd, cpx, cpy);
  13071. break;
  13072. case 'L':
  13073. cpx = p[off++];
  13074. cpy = p[off++];
  13075. cmd = CMD.L;
  13076. path.addData(cmd, cpx, cpy);
  13077. break;
  13078. case 'm':
  13079. cpx += p[off++];
  13080. cpy += p[off++];
  13081. cmd = CMD.M;
  13082. path.addData(cmd, cpx, cpy);
  13083. subpathX = cpx;
  13084. subpathY = cpy;
  13085. cmdStr = 'l';
  13086. break;
  13087. case 'M':
  13088. cpx = p[off++];
  13089. cpy = p[off++];
  13090. cmd = CMD.M;
  13091. path.addData(cmd, cpx, cpy);
  13092. subpathX = cpx;
  13093. subpathY = cpy;
  13094. cmdStr = 'L';
  13095. break;
  13096. case 'h':
  13097. cpx += p[off++];
  13098. cmd = CMD.L;
  13099. path.addData(cmd, cpx, cpy);
  13100. break;
  13101. case 'H':
  13102. cpx = p[off++];
  13103. cmd = CMD.L;
  13104. path.addData(cmd, cpx, cpy);
  13105. break;
  13106. case 'v':
  13107. cpy += p[off++];
  13108. cmd = CMD.L;
  13109. path.addData(cmd, cpx, cpy);
  13110. break;
  13111. case 'V':
  13112. cpy = p[off++];
  13113. cmd = CMD.L;
  13114. path.addData(cmd, cpx, cpy);
  13115. break;
  13116. case 'C':
  13117. cmd = CMD.C;
  13118. path.addData(
  13119. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13120. );
  13121. cpx = p[off - 2];
  13122. cpy = p[off - 1];
  13123. break;
  13124. case 'c':
  13125. cmd = CMD.C;
  13126. path.addData(
  13127. cmd,
  13128. p[off++] + cpx, p[off++] + cpy,
  13129. p[off++] + cpx, p[off++] + cpy,
  13130. p[off++] + cpx, p[off++] + cpy
  13131. );
  13132. cpx += p[off - 2];
  13133. cpy += p[off - 1];
  13134. break;
  13135. case 'S':
  13136. ctlPtx = cpx;
  13137. ctlPty = cpy;
  13138. var len = path.len();
  13139. var pathData = path.data;
  13140. if (prevCmd === CMD.C) {
  13141. ctlPtx += cpx - pathData[len - 4];
  13142. ctlPty += cpy - pathData[len - 3];
  13143. }
  13144. cmd = CMD.C;
  13145. x1 = p[off++];
  13146. y1 = p[off++];
  13147. cpx = p[off++];
  13148. cpy = p[off++];
  13149. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13150. break;
  13151. case 's':
  13152. ctlPtx = cpx;
  13153. ctlPty = cpy;
  13154. var len = path.len();
  13155. var pathData = path.data;
  13156. if (prevCmd === CMD.C) {
  13157. ctlPtx += cpx - pathData[len - 4];
  13158. ctlPty += cpy - pathData[len - 3];
  13159. }
  13160. cmd = CMD.C;
  13161. x1 = cpx + p[off++];
  13162. y1 = cpy + p[off++];
  13163. cpx += p[off++];
  13164. cpy += p[off++];
  13165. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13166. break;
  13167. case 'Q':
  13168. x1 = p[off++];
  13169. y1 = p[off++];
  13170. cpx = p[off++];
  13171. cpy = p[off++];
  13172. cmd = CMD.Q;
  13173. path.addData(cmd, x1, y1, cpx, cpy);
  13174. break;
  13175. case 'q':
  13176. x1 = p[off++] + cpx;
  13177. y1 = p[off++] + cpy;
  13178. cpx += p[off++];
  13179. cpy += p[off++];
  13180. cmd = CMD.Q;
  13181. path.addData(cmd, x1, y1, cpx, cpy);
  13182. break;
  13183. case 'T':
  13184. ctlPtx = cpx;
  13185. ctlPty = cpy;
  13186. var len = path.len();
  13187. var pathData = path.data;
  13188. if (prevCmd === CMD.Q) {
  13189. ctlPtx += cpx - pathData[len - 4];
  13190. ctlPty += cpy - pathData[len - 3];
  13191. }
  13192. cpx = p[off++];
  13193. cpy = p[off++];
  13194. cmd = CMD.Q;
  13195. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13196. break;
  13197. case 't':
  13198. ctlPtx = cpx;
  13199. ctlPty = cpy;
  13200. var len = path.len();
  13201. var pathData = path.data;
  13202. if (prevCmd === CMD.Q) {
  13203. ctlPtx += cpx - pathData[len - 4];
  13204. ctlPty += cpy - pathData[len - 3];
  13205. }
  13206. cpx += p[off++];
  13207. cpy += p[off++];
  13208. cmd = CMD.Q;
  13209. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13210. break;
  13211. case 'A':
  13212. rx = p[off++];
  13213. ry = p[off++];
  13214. psi = p[off++];
  13215. fa = p[off++];
  13216. fs = p[off++];
  13217. x1 = cpx, y1 = cpy;
  13218. cpx = p[off++];
  13219. cpy = p[off++];
  13220. cmd = CMD.A;
  13221. processArc(
  13222. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13223. );
  13224. break;
  13225. case 'a':
  13226. rx = p[off++];
  13227. ry = p[off++];
  13228. psi = p[off++];
  13229. fa = p[off++];
  13230. fs = p[off++];
  13231. x1 = cpx, y1 = cpy;
  13232. cpx += p[off++];
  13233. cpy += p[off++];
  13234. cmd = CMD.A;
  13235. processArc(
  13236. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13237. );
  13238. break;
  13239. }
  13240. }
  13241. if (cmdStr === 'z' || cmdStr === 'Z') {
  13242. cmd = CMD.Z;
  13243. path.addData(cmd);
  13244. // z may be in the middle of the path.
  13245. cpx = subpathX;
  13246. cpy = subpathY;
  13247. }
  13248. prevCmd = cmd;
  13249. }
  13250. path.toStatic();
  13251. return path;
  13252. }
  13253. // TODO Optimize double memory cost problem
  13254. function createPathOptions(str, opts) {
  13255. var pathProxy = createPathProxyFromString(str);
  13256. opts = opts || {};
  13257. opts.buildPath = function (path) {
  13258. if (path.setData) {
  13259. path.setData(pathProxy.data);
  13260. // Svg and vml renderer don't have context
  13261. var ctx = path.getContext();
  13262. if (ctx) {
  13263. path.rebuildPath(ctx);
  13264. }
  13265. }
  13266. else {
  13267. var ctx = path;
  13268. pathProxy.rebuildPath(ctx);
  13269. }
  13270. };
  13271. opts.applyTransform = function (m) {
  13272. transformPath(pathProxy, m);
  13273. this.dirty(true);
  13274. };
  13275. return opts;
  13276. }
  13277. /**
  13278. * Create a Path object from path string data
  13279. * http://www.w3.org/TR/SVG/paths.html#PathData
  13280. * @param {Object} opts Other options
  13281. */
  13282. function createFromString(str, opts) {
  13283. return new Path(createPathOptions(str, opts));
  13284. }
  13285. /**
  13286. * Create a Path class from path string data
  13287. * @param {string} str
  13288. * @param {Object} opts Other options
  13289. */
  13290. function extendFromString(str, opts) {
  13291. return Path.extend(createPathOptions(str, opts));
  13292. }
  13293. /**
  13294. * Merge multiple paths
  13295. */
  13296. // TODO Apply transform
  13297. // TODO stroke dash
  13298. // TODO Optimize double memory cost problem
  13299. function mergePath$1(pathEls, opts) {
  13300. var pathList = [];
  13301. var len = pathEls.length;
  13302. for (var i = 0; i < len; i++) {
  13303. var pathEl = pathEls[i];
  13304. if (!pathEl.path) {
  13305. pathEl.createPathProxy();
  13306. }
  13307. if (pathEl.__dirtyPath) {
  13308. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13309. }
  13310. pathList.push(pathEl.path);
  13311. }
  13312. var pathBundle = new Path(opts);
  13313. // Need path proxy.
  13314. pathBundle.createPathProxy();
  13315. pathBundle.buildPath = function (path) {
  13316. path.appendPath(pathList);
  13317. // Svg and vml renderer don't have context
  13318. var ctx = path.getContext();
  13319. if (ctx) {
  13320. path.rebuildPath(ctx);
  13321. }
  13322. };
  13323. return pathBundle;
  13324. }
  13325. /**
  13326. * @alias zrender/graphic/Text
  13327. * @extends module:zrender/graphic/Displayable
  13328. * @constructor
  13329. * @param {Object} opts
  13330. */
  13331. var Text = function (opts) { // jshint ignore:line
  13332. Displayable.call(this, opts);
  13333. };
  13334. Text.prototype = {
  13335. constructor: Text,
  13336. type: 'text',
  13337. brush: function (ctx, prevEl) {
  13338. var style = this.style;
  13339. // Optimize, avoid normalize every time.
  13340. this.__dirty && normalizeTextStyle(style, true);
  13341. // Use props with prefix 'text'.
  13342. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  13343. style.shadowOffsetX = style.shadowOffsetY = null;
  13344. var text = style.text;
  13345. // Convert to string
  13346. text != null && (text += '');
  13347. // Do not apply style.bind in Text node. Because the real bind job
  13348. // is in textHelper.renderText, and performance of text render should
  13349. // be considered.
  13350. // style.bind(ctx, this, prevEl);
  13351. if (!needDrawText(text, style)) {
  13352. // The current el.style is not applied
  13353. // and should not be used as cache.
  13354. ctx.__attrCachedBy = ContextCachedBy.NONE;
  13355. return;
  13356. }
  13357. this.setTransform(ctx);
  13358. renderText(this, ctx, text, style, null, prevEl);
  13359. this.restoreTransform(ctx);
  13360. },
  13361. getBoundingRect: function () {
  13362. var style = this.style;
  13363. // Optimize, avoid normalize every time.
  13364. this.__dirty && normalizeTextStyle(style, true);
  13365. if (!this._rect) {
  13366. var text = style.text;
  13367. text != null ? (text += '') : (text = '');
  13368. var rect = getBoundingRect(
  13369. style.text + '',
  13370. style.font,
  13371. style.textAlign,
  13372. style.textVerticalAlign,
  13373. style.textPadding,
  13374. style.textLineHeight,
  13375. style.rich
  13376. );
  13377. rect.x += style.x || 0;
  13378. rect.y += style.y || 0;
  13379. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13380. var w = style.textStrokeWidth;
  13381. rect.x -= w / 2;
  13382. rect.y -= w / 2;
  13383. rect.width += w;
  13384. rect.height += w;
  13385. }
  13386. this._rect = rect;
  13387. }
  13388. return this._rect;
  13389. }
  13390. };
  13391. inherits(Text, Displayable);
  13392. /**
  13393. * 圆形
  13394. * @module zrender/shape/Circle
  13395. */
  13396. var Circle = Path.extend({
  13397. type: 'circle',
  13398. shape: {
  13399. cx: 0,
  13400. cy: 0,
  13401. r: 0
  13402. },
  13403. buildPath: function (ctx, shape, inBundle) {
  13404. // Better stroking in ShapeBundle
  13405. // Always do it may have performence issue ( fill may be 2x more cost)
  13406. if (inBundle) {
  13407. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13408. }
  13409. // else {
  13410. // if (ctx.allocate && !ctx.data.length) {
  13411. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13412. // }
  13413. // }
  13414. // Better stroking in ShapeBundle
  13415. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13416. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13417. }
  13418. });
  13419. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13420. // where exception "unexpected call to method or property access"
  13421. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13422. // whose area size is zero is drawn and ctx.clip() is called and
  13423. // shadowBlur is set. See #4572, #3112, #5777.
  13424. // (e.g.,
  13425. // ctx.moveTo(10, 10);
  13426. // ctx.lineTo(20, 10);
  13427. // ctx.closePath();
  13428. // ctx.clip();
  13429. // ctx.shadowBlur = 10;
  13430. // ...
  13431. // ctx.fill();
  13432. // )
  13433. var shadowTemp = [
  13434. ['shadowBlur', 0],
  13435. ['shadowColor', '#000'],
  13436. ['shadowOffsetX', 0],
  13437. ['shadowOffsetY', 0]
  13438. ];
  13439. var fixClipWithShadow = function (orignalBrush) {
  13440. // version string can be: '11.0'
  13441. return (env$1.browser.ie && env$1.browser.version >= 11)
  13442. ? function () {
  13443. var clipPaths = this.__clipPaths;
  13444. var style = this.style;
  13445. var modified;
  13446. if (clipPaths) {
  13447. for (var i = 0; i < clipPaths.length; i++) {
  13448. var clipPath = clipPaths[i];
  13449. var shape = clipPath && clipPath.shape;
  13450. var type = clipPath && clipPath.type;
  13451. if (shape && (
  13452. (type === 'sector' && shape.startAngle === shape.endAngle)
  13453. || (type === 'rect' && (!shape.width || !shape.height))
  13454. )) {
  13455. for (var j = 0; j < shadowTemp.length; j++) {
  13456. // It is save to put shadowTemp static, because shadowTemp
  13457. // will be all modified each item brush called.
  13458. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13459. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13460. }
  13461. modified = true;
  13462. break;
  13463. }
  13464. }
  13465. }
  13466. orignalBrush.apply(this, arguments);
  13467. if (modified) {
  13468. for (var j = 0; j < shadowTemp.length; j++) {
  13469. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13470. }
  13471. }
  13472. }
  13473. : orignalBrush;
  13474. };
  13475. /**
  13476. * 扇形
  13477. * @module zrender/graphic/shape/Sector
  13478. */
  13479. var Sector = Path.extend({
  13480. type: 'sector',
  13481. shape: {
  13482. cx: 0,
  13483. cy: 0,
  13484. r0: 0,
  13485. r: 0,
  13486. startAngle: 0,
  13487. endAngle: Math.PI * 2,
  13488. clockwise: true
  13489. },
  13490. brush: fixClipWithShadow(Path.prototype.brush),
  13491. buildPath: function (ctx, shape) {
  13492. var x = shape.cx;
  13493. var y = shape.cy;
  13494. var r0 = Math.max(shape.r0 || 0, 0);
  13495. var r = Math.max(shape.r, 0);
  13496. var startAngle = shape.startAngle;
  13497. var endAngle = shape.endAngle;
  13498. var clockwise = shape.clockwise;
  13499. var unitX = Math.cos(startAngle);
  13500. var unitY = Math.sin(startAngle);
  13501. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13502. ctx.lineTo(unitX * r + x, unitY * r + y);
  13503. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13504. ctx.lineTo(
  13505. Math.cos(endAngle) * r0 + x,
  13506. Math.sin(endAngle) * r0 + y
  13507. );
  13508. if (r0 !== 0) {
  13509. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13510. }
  13511. ctx.closePath();
  13512. }
  13513. });
  13514. /**
  13515. * 圆环
  13516. * @module zrender/graphic/shape/Ring
  13517. */
  13518. var Ring = Path.extend({
  13519. type: 'ring',
  13520. shape: {
  13521. cx: 0,
  13522. cy: 0,
  13523. r: 0,
  13524. r0: 0
  13525. },
  13526. buildPath: function (ctx, shape) {
  13527. var x = shape.cx;
  13528. var y = shape.cy;
  13529. var PI2 = Math.PI * 2;
  13530. ctx.moveTo(x + shape.r, y);
  13531. ctx.arc(x, y, shape.r, 0, PI2, false);
  13532. ctx.moveTo(x + shape.r0, y);
  13533. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13534. }
  13535. });
  13536. /**
  13537. * Catmull-Rom spline 插值折线
  13538. * @module zrender/shape/util/smoothSpline
  13539. * @author pissang (https://www.github.com/pissang)
  13540. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13541. * errorrik (errorrik@gmail.com)
  13542. */
  13543. /**
  13544. * @inner
  13545. */
  13546. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13547. var v0 = (p2 - p0) * 0.5;
  13548. var v1 = (p3 - p1) * 0.5;
  13549. return (2 * (p1 - p2) + v0 + v1) * t3
  13550. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13551. + v0 * t + p1;
  13552. }
  13553. /**
  13554. * @alias module:zrender/shape/util/smoothSpline
  13555. * @param {Array} points 线段顶点数组
  13556. * @param {boolean} isLoop
  13557. * @return {Array}
  13558. */
  13559. var smoothSpline = function (points, isLoop) {
  13560. var len$$1 = points.length;
  13561. var ret = [];
  13562. var distance$$1 = 0;
  13563. for (var i = 1; i < len$$1; i++) {
  13564. distance$$1 += distance(points[i - 1], points[i]);
  13565. }
  13566. var segs = distance$$1 / 2;
  13567. segs = segs < len$$1 ? len$$1 : segs;
  13568. for (var i = 0; i < segs; i++) {
  13569. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13570. var idx = Math.floor(pos);
  13571. var w = pos - idx;
  13572. var p0;
  13573. var p1 = points[idx % len$$1];
  13574. var p2;
  13575. var p3;
  13576. if (!isLoop) {
  13577. p0 = points[idx === 0 ? idx : idx - 1];
  13578. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13579. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13580. }
  13581. else {
  13582. p0 = points[(idx - 1 + len$$1) % len$$1];
  13583. p2 = points[(idx + 1) % len$$1];
  13584. p3 = points[(idx + 2) % len$$1];
  13585. }
  13586. var w2 = w * w;
  13587. var w3 = w * w2;
  13588. ret.push([
  13589. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13590. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13591. ]);
  13592. }
  13593. return ret;
  13594. };
  13595. /**
  13596. * 贝塞尔平滑曲线
  13597. * @module zrender/shape/util/smoothBezier
  13598. * @author pissang (https://www.github.com/pissang)
  13599. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13600. * errorrik (errorrik@gmail.com)
  13601. */
  13602. /**
  13603. * 贝塞尔平滑曲线
  13604. * @alias module:zrender/shape/util/smoothBezier
  13605. * @param {Array} points 线段顶点数组
  13606. * @param {number} smooth 平滑等级, 0-1
  13607. * @param {boolean} isLoop
  13608. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13609. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13610. * 整个折线的包围盒做一个并集用来约束控制点。
  13611. * @param {Array} 计算出来的控制点数组
  13612. */
  13613. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13614. var cps = [];
  13615. var v = [];
  13616. var v1 = [];
  13617. var v2 = [];
  13618. var prevPoint;
  13619. var nextPoint;
  13620. var min$$1;
  13621. var max$$1;
  13622. if (constraint) {
  13623. min$$1 = [Infinity, Infinity];
  13624. max$$1 = [-Infinity, -Infinity];
  13625. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13626. min(min$$1, min$$1, points[i]);
  13627. max(max$$1, max$$1, points[i]);
  13628. }
  13629. // 与指定的包围盒做并集
  13630. min(min$$1, min$$1, constraint[0]);
  13631. max(max$$1, max$$1, constraint[1]);
  13632. }
  13633. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13634. var point = points[i];
  13635. if (isLoop) {
  13636. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13637. nextPoint = points[(i + 1) % len$$1];
  13638. }
  13639. else {
  13640. if (i === 0 || i === len$$1 - 1) {
  13641. cps.push(clone$1(points[i]));
  13642. continue;
  13643. }
  13644. else {
  13645. prevPoint = points[i - 1];
  13646. nextPoint = points[i + 1];
  13647. }
  13648. }
  13649. sub(v, nextPoint, prevPoint);
  13650. // use degree to scale the handle length
  13651. scale(v, v, smooth);
  13652. var d0 = distance(point, prevPoint);
  13653. var d1 = distance(point, nextPoint);
  13654. var sum = d0 + d1;
  13655. if (sum !== 0) {
  13656. d0 /= sum;
  13657. d1 /= sum;
  13658. }
  13659. scale(v1, v, -d0);
  13660. scale(v2, v, d1);
  13661. var cp0 = add([], point, v1);
  13662. var cp1 = add([], point, v2);
  13663. if (constraint) {
  13664. max(cp0, cp0, min$$1);
  13665. min(cp0, cp0, max$$1);
  13666. max(cp1, cp1, min$$1);
  13667. min(cp1, cp1, max$$1);
  13668. }
  13669. cps.push(cp0);
  13670. cps.push(cp1);
  13671. }
  13672. if (isLoop) {
  13673. cps.push(cps.shift());
  13674. }
  13675. return cps;
  13676. };
  13677. function buildPath$1(ctx, shape, closePath) {
  13678. var points = shape.points;
  13679. var smooth = shape.smooth;
  13680. if (points && points.length >= 2) {
  13681. if (smooth && smooth !== 'spline') {
  13682. var controlPoints = smoothBezier(
  13683. points, smooth, closePath, shape.smoothConstraint
  13684. );
  13685. ctx.moveTo(points[0][0], points[0][1]);
  13686. var len = points.length;
  13687. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13688. var cp1 = controlPoints[i * 2];
  13689. var cp2 = controlPoints[i * 2 + 1];
  13690. var p = points[(i + 1) % len];
  13691. ctx.bezierCurveTo(
  13692. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13693. );
  13694. }
  13695. }
  13696. else {
  13697. if (smooth === 'spline') {
  13698. points = smoothSpline(points, closePath);
  13699. }
  13700. ctx.moveTo(points[0][0], points[0][1]);
  13701. for (var i = 1, l = points.length; i < l; i++) {
  13702. ctx.lineTo(points[i][0], points[i][1]);
  13703. }
  13704. }
  13705. closePath && ctx.closePath();
  13706. }
  13707. }
  13708. /**
  13709. * 多边形
  13710. * @module zrender/shape/Polygon
  13711. */
  13712. var Polygon = Path.extend({
  13713. type: 'polygon',
  13714. shape: {
  13715. points: null,
  13716. smooth: false,
  13717. smoothConstraint: null
  13718. },
  13719. buildPath: function (ctx, shape) {
  13720. buildPath$1(ctx, shape, true);
  13721. }
  13722. });
  13723. /**
  13724. * @module zrender/graphic/shape/Polyline
  13725. */
  13726. var Polyline = Path.extend({
  13727. type: 'polyline',
  13728. shape: {
  13729. points: null,
  13730. smooth: false,
  13731. smoothConstraint: null
  13732. },
  13733. style: {
  13734. stroke: '#000',
  13735. fill: null
  13736. },
  13737. buildPath: function (ctx, shape) {
  13738. buildPath$1(ctx, shape, false);
  13739. }
  13740. });
  13741. /**
  13742. * Sub-pixel optimize for canvas rendering, prevent from blur
  13743. * when rendering a thin vertical/horizontal line.
  13744. */
  13745. var round$1 = Math.round;
  13746. /**
  13747. * Sub pixel optimize line for canvas
  13748. *
  13749. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13750. * `outputShape` and `inputShape` can be the same object.
  13751. * `outputShape` object can be used repeatly, because all of
  13752. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  13753. * @param {Object} [inputShape]
  13754. * @param {number} [inputShape.x1]
  13755. * @param {number} [inputShape.y1]
  13756. * @param {number} [inputShape.x2]
  13757. * @param {number} [inputShape.y2]
  13758. * @param {Object} [style]
  13759. * @param {number} [style.lineWidth]
  13760. */
  13761. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  13762. var lineWidth = style && style.lineWidth;
  13763. if (!inputShape || !lineWidth) {
  13764. return;
  13765. }
  13766. var x1 = inputShape.x1;
  13767. var x2 = inputShape.x2;
  13768. var y1 = inputShape.y1;
  13769. var y2 = inputShape.y2;
  13770. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  13771. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  13772. }
  13773. else {
  13774. outputShape.x1 = x1;
  13775. outputShape.x2 = x2;
  13776. }
  13777. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  13778. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  13779. }
  13780. else {
  13781. outputShape.y1 = y1;
  13782. outputShape.y2 = y2;
  13783. }
  13784. }
  13785. /**
  13786. * Sub pixel optimize rect for canvas
  13787. *
  13788. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13789. * `outputShape` and `inputShape` can be the same object.
  13790. * `outputShape` object can be used repeatly, because all of
  13791. * the `x`, `y`, `width`, `height` will be assigned in this method.
  13792. * @param {Object} [inputShape]
  13793. * @param {number} [inputShape.x]
  13794. * @param {number} [inputShape.y]
  13795. * @param {number} [inputShape.width]
  13796. * @param {number} [inputShape.height]
  13797. * @param {Object} [style]
  13798. * @param {number} [style.lineWidth]
  13799. */
  13800. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  13801. var lineWidth = style && style.lineWidth;
  13802. if (!inputShape || !lineWidth) {
  13803. return;
  13804. }
  13805. var originX = inputShape.x;
  13806. var originY = inputShape.y;
  13807. var originWidth = inputShape.width;
  13808. var originHeight = inputShape.height;
  13809. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  13810. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  13811. outputShape.width = Math.max(
  13812. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  13813. originWidth === 0 ? 0 : 1
  13814. );
  13815. outputShape.height = Math.max(
  13816. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  13817. originHeight === 0 ? 0 : 1
  13818. );
  13819. }
  13820. /**
  13821. * Sub pixel optimize for canvas
  13822. *
  13823. * @param {number} position Coordinate, such as x, y
  13824. * @param {number} lineWidth Should be nonnegative integer.
  13825. * @param {boolean=} positiveOrNegative Default false (negative).
  13826. * @return {number} Optimized position.
  13827. */
  13828. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  13829. // Assure that (position + lineWidth / 2) is near integer edge,
  13830. // otherwise line will be fuzzy in canvas.
  13831. var doubledPosition = round$1(position * 2);
  13832. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  13833. ? doubledPosition / 2
  13834. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13835. }
  13836. /**
  13837. * 矩形
  13838. * @module zrender/graphic/shape/Rect
  13839. */
  13840. // Avoid create repeatly.
  13841. var subPixelOptimizeOutputShape = {};
  13842. var Rect = Path.extend({
  13843. type: 'rect',
  13844. shape: {
  13845. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13846. // r缩写为1 相当于 [1, 1, 1, 1]
  13847. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13848. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13849. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13850. r: 0,
  13851. x: 0,
  13852. y: 0,
  13853. width: 0,
  13854. height: 0
  13855. },
  13856. buildPath: function (ctx, shape) {
  13857. var x;
  13858. var y;
  13859. var width;
  13860. var height;
  13861. if (this.subPixelOptimize) {
  13862. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  13863. x = subPixelOptimizeOutputShape.x;
  13864. y = subPixelOptimizeOutputShape.y;
  13865. width = subPixelOptimizeOutputShape.width;
  13866. height = subPixelOptimizeOutputShape.height;
  13867. subPixelOptimizeOutputShape.r = shape.r;
  13868. shape = subPixelOptimizeOutputShape;
  13869. }
  13870. else {
  13871. x = shape.x;
  13872. y = shape.y;
  13873. width = shape.width;
  13874. height = shape.height;
  13875. }
  13876. if (!shape.r) {
  13877. ctx.rect(x, y, width, height);
  13878. }
  13879. else {
  13880. buildPath(ctx, shape);
  13881. }
  13882. ctx.closePath();
  13883. return;
  13884. }
  13885. });
  13886. /**
  13887. * 直线
  13888. * @module zrender/graphic/shape/Line
  13889. */
  13890. // Avoid create repeatly.
  13891. var subPixelOptimizeOutputShape$1 = {};
  13892. var Line = Path.extend({
  13893. type: 'line',
  13894. shape: {
  13895. // Start point
  13896. x1: 0,
  13897. y1: 0,
  13898. // End point
  13899. x2: 0,
  13900. y2: 0,
  13901. percent: 1
  13902. },
  13903. style: {
  13904. stroke: '#000',
  13905. fill: null
  13906. },
  13907. buildPath: function (ctx, shape) {
  13908. var x1;
  13909. var y1;
  13910. var x2;
  13911. var y2;
  13912. if (this.subPixelOptimize) {
  13913. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  13914. x1 = subPixelOptimizeOutputShape$1.x1;
  13915. y1 = subPixelOptimizeOutputShape$1.y1;
  13916. x2 = subPixelOptimizeOutputShape$1.x2;
  13917. y2 = subPixelOptimizeOutputShape$1.y2;
  13918. }
  13919. else {
  13920. x1 = shape.x1;
  13921. y1 = shape.y1;
  13922. x2 = shape.x2;
  13923. y2 = shape.y2;
  13924. }
  13925. var percent = shape.percent;
  13926. if (percent === 0) {
  13927. return;
  13928. }
  13929. ctx.moveTo(x1, y1);
  13930. if (percent < 1) {
  13931. x2 = x1 * (1 - percent) + x2 * percent;
  13932. y2 = y1 * (1 - percent) + y2 * percent;
  13933. }
  13934. ctx.lineTo(x2, y2);
  13935. },
  13936. /**
  13937. * Get point at percent
  13938. * @param {number} percent
  13939. * @return {Array.<number>}
  13940. */
  13941. pointAt: function (p) {
  13942. var shape = this.shape;
  13943. return [
  13944. shape.x1 * (1 - p) + shape.x2 * p,
  13945. shape.y1 * (1 - p) + shape.y2 * p
  13946. ];
  13947. }
  13948. });
  13949. /**
  13950. * 贝塞尔曲线
  13951. * @module zrender/shape/BezierCurve
  13952. */
  13953. var out = [];
  13954. function someVectorAt(shape, t, isTangent) {
  13955. var cpx2 = shape.cpx2;
  13956. var cpy2 = shape.cpy2;
  13957. if (cpx2 === null || cpy2 === null) {
  13958. return [
  13959. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13960. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13961. ];
  13962. }
  13963. else {
  13964. return [
  13965. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13966. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13967. ];
  13968. }
  13969. }
  13970. var BezierCurve = Path.extend({
  13971. type: 'bezier-curve',
  13972. shape: {
  13973. x1: 0,
  13974. y1: 0,
  13975. x2: 0,
  13976. y2: 0,
  13977. cpx1: 0,
  13978. cpy1: 0,
  13979. // cpx2: 0,
  13980. // cpy2: 0
  13981. // Curve show percent, for animating
  13982. percent: 1
  13983. },
  13984. style: {
  13985. stroke: '#000',
  13986. fill: null
  13987. },
  13988. buildPath: function (ctx, shape) {
  13989. var x1 = shape.x1;
  13990. var y1 = shape.y1;
  13991. var x2 = shape.x2;
  13992. var y2 = shape.y2;
  13993. var cpx1 = shape.cpx1;
  13994. var cpy1 = shape.cpy1;
  13995. var cpx2 = shape.cpx2;
  13996. var cpy2 = shape.cpy2;
  13997. var percent = shape.percent;
  13998. if (percent === 0) {
  13999. return;
  14000. }
  14001. ctx.moveTo(x1, y1);
  14002. if (cpx2 == null || cpy2 == null) {
  14003. if (percent < 1) {
  14004. quadraticSubdivide(
  14005. x1, cpx1, x2, percent, out
  14006. );
  14007. cpx1 = out[1];
  14008. x2 = out[2];
  14009. quadraticSubdivide(
  14010. y1, cpy1, y2, percent, out
  14011. );
  14012. cpy1 = out[1];
  14013. y2 = out[2];
  14014. }
  14015. ctx.quadraticCurveTo(
  14016. cpx1, cpy1,
  14017. x2, y2
  14018. );
  14019. }
  14020. else {
  14021. if (percent < 1) {
  14022. cubicSubdivide(
  14023. x1, cpx1, cpx2, x2, percent, out
  14024. );
  14025. cpx1 = out[1];
  14026. cpx2 = out[2];
  14027. x2 = out[3];
  14028. cubicSubdivide(
  14029. y1, cpy1, cpy2, y2, percent, out
  14030. );
  14031. cpy1 = out[1];
  14032. cpy2 = out[2];
  14033. y2 = out[3];
  14034. }
  14035. ctx.bezierCurveTo(
  14036. cpx1, cpy1,
  14037. cpx2, cpy2,
  14038. x2, y2
  14039. );
  14040. }
  14041. },
  14042. /**
  14043. * Get point at percent
  14044. * @param {number} t
  14045. * @return {Array.<number>}
  14046. */
  14047. pointAt: function (t) {
  14048. return someVectorAt(this.shape, t, false);
  14049. },
  14050. /**
  14051. * Get tangent at percent
  14052. * @param {number} t
  14053. * @return {Array.<number>}
  14054. */
  14055. tangentAt: function (t) {
  14056. var p = someVectorAt(this.shape, t, true);
  14057. return normalize(p, p);
  14058. }
  14059. });
  14060. /**
  14061. * 圆弧
  14062. * @module zrender/graphic/shape/Arc
  14063. */
  14064. var Arc = Path.extend({
  14065. type: 'arc',
  14066. shape: {
  14067. cx: 0,
  14068. cy: 0,
  14069. r: 0,
  14070. startAngle: 0,
  14071. endAngle: Math.PI * 2,
  14072. clockwise: true
  14073. },
  14074. style: {
  14075. stroke: '#000',
  14076. fill: null
  14077. },
  14078. buildPath: function (ctx, shape) {
  14079. var x = shape.cx;
  14080. var y = shape.cy;
  14081. var r = Math.max(shape.r, 0);
  14082. var startAngle = shape.startAngle;
  14083. var endAngle = shape.endAngle;
  14084. var clockwise = shape.clockwise;
  14085. var unitX = Math.cos(startAngle);
  14086. var unitY = Math.sin(startAngle);
  14087. ctx.moveTo(unitX * r + x, unitY * r + y);
  14088. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14089. }
  14090. });
  14091. // CompoundPath to improve performance
  14092. var CompoundPath = Path.extend({
  14093. type: 'compound',
  14094. shape: {
  14095. paths: null
  14096. },
  14097. _updatePathDirty: function () {
  14098. var dirtyPath = this.__dirtyPath;
  14099. var paths = this.shape.paths;
  14100. for (var i = 0; i < paths.length; i++) {
  14101. // Mark as dirty if any subpath is dirty
  14102. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14103. }
  14104. this.__dirtyPath = dirtyPath;
  14105. this.__dirty = this.__dirty || dirtyPath;
  14106. },
  14107. beforeBrush: function () {
  14108. this._updatePathDirty();
  14109. var paths = this.shape.paths || [];
  14110. var scale = this.getGlobalScale();
  14111. // Update path scale
  14112. for (var i = 0; i < paths.length; i++) {
  14113. if (!paths[i].path) {
  14114. paths[i].createPathProxy();
  14115. }
  14116. paths[i].path.setScale(scale[0], scale[1]);
  14117. }
  14118. },
  14119. buildPath: function (ctx, shape) {
  14120. var paths = shape.paths || [];
  14121. for (var i = 0; i < paths.length; i++) {
  14122. paths[i].buildPath(ctx, paths[i].shape, true);
  14123. }
  14124. },
  14125. afterBrush: function () {
  14126. var paths = this.shape.paths || [];
  14127. for (var i = 0; i < paths.length; i++) {
  14128. paths[i].__dirtyPath = false;
  14129. }
  14130. },
  14131. getBoundingRect: function () {
  14132. this._updatePathDirty();
  14133. return Path.prototype.getBoundingRect.call(this);
  14134. }
  14135. });
  14136. /**
  14137. * @param {Array.<Object>} colorStops
  14138. */
  14139. var Gradient = function (colorStops) {
  14140. this.colorStops = colorStops || [];
  14141. };
  14142. Gradient.prototype = {
  14143. constructor: Gradient,
  14144. addColorStop: function (offset, color) {
  14145. this.colorStops.push({
  14146. offset: offset,
  14147. color: color
  14148. });
  14149. }
  14150. };
  14151. /**
  14152. * x, y, x2, y2 are all percent from 0 to 1
  14153. * @param {number} [x=0]
  14154. * @param {number} [y=0]
  14155. * @param {number} [x2=1]
  14156. * @param {number} [y2=0]
  14157. * @param {Array.<Object>} colorStops
  14158. * @param {boolean} [globalCoord=false]
  14159. */
  14160. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  14161. // Should do nothing more in this constructor. Because gradient can be
  14162. // declard by `color: {type: 'linear', colorStops: ...}`, where
  14163. // this constructor will not be called.
  14164. this.x = x == null ? 0 : x;
  14165. this.y = y == null ? 0 : y;
  14166. this.x2 = x2 == null ? 1 : x2;
  14167. this.y2 = y2 == null ? 0 : y2;
  14168. // Can be cloned
  14169. this.type = 'linear';
  14170. // If use global coord
  14171. this.global = globalCoord || false;
  14172. Gradient.call(this, colorStops);
  14173. };
  14174. LinearGradient.prototype = {
  14175. constructor: LinearGradient
  14176. };
  14177. inherits(LinearGradient, Gradient);
  14178. /**
  14179. * x, y, r are all percent from 0 to 1
  14180. * @param {number} [x=0.5]
  14181. * @param {number} [y=0.5]
  14182. * @param {number} [r=0.5]
  14183. * @param {Array.<Object>} [colorStops]
  14184. * @param {boolean} [globalCoord=false]
  14185. */
  14186. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14187. // Should do nothing more in this constructor. Because gradient can be
  14188. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14189. // this constructor will not be called.
  14190. this.x = x == null ? 0.5 : x;
  14191. this.y = y == null ? 0.5 : y;
  14192. this.r = r == null ? 0.5 : r;
  14193. // Can be cloned
  14194. this.type = 'radial';
  14195. // If use global coord
  14196. this.global = globalCoord || false;
  14197. Gradient.call(this, colorStops);
  14198. };
  14199. RadialGradient.prototype = {
  14200. constructor: RadialGradient
  14201. };
  14202. inherits(RadialGradient, Gradient);
  14203. /**
  14204. * Displayable for incremental rendering. It will be rendered in a separate layer
  14205. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14206. * addDisplayables will render the added displayables incremetally.
  14207. *
  14208. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14209. */
  14210. // TODO Style override ?
  14211. function IncrementalDisplayble(opts) {
  14212. Displayable.call(this, opts);
  14213. this._displayables = [];
  14214. this._temporaryDisplayables = [];
  14215. this._cursor = 0;
  14216. this.notClear = true;
  14217. }
  14218. IncrementalDisplayble.prototype.incremental = true;
  14219. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14220. this._displayables = [];
  14221. this._temporaryDisplayables = [];
  14222. this._cursor = 0;
  14223. this.dirty();
  14224. this.notClear = false;
  14225. };
  14226. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14227. if (notPersistent) {
  14228. this._temporaryDisplayables.push(displayable);
  14229. }
  14230. else {
  14231. this._displayables.push(displayable);
  14232. }
  14233. this.dirty();
  14234. };
  14235. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14236. notPersistent = notPersistent || false;
  14237. for (var i = 0; i < displayables.length; i++) {
  14238. this.addDisplayable(displayables[i], notPersistent);
  14239. }
  14240. };
  14241. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14242. for (var i = this._cursor; i < this._displayables.length; i++) {
  14243. cb && cb(this._displayables[i]);
  14244. }
  14245. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14246. cb && cb(this._temporaryDisplayables[i]);
  14247. }
  14248. };
  14249. IncrementalDisplayble.prototype.update = function () {
  14250. this.updateTransform();
  14251. for (var i = this._cursor; i < this._displayables.length; i++) {
  14252. var displayable = this._displayables[i];
  14253. // PENDING
  14254. displayable.parent = this;
  14255. displayable.update();
  14256. displayable.parent = null;
  14257. }
  14258. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14259. var displayable = this._temporaryDisplayables[i];
  14260. // PENDING
  14261. displayable.parent = this;
  14262. displayable.update();
  14263. displayable.parent = null;
  14264. }
  14265. };
  14266. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14267. // Render persistant displayables.
  14268. for (var i = this._cursor; i < this._displayables.length; i++) {
  14269. var displayable = this._displayables[i];
  14270. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14271. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14272. displayable.afterBrush && displayable.afterBrush(ctx);
  14273. }
  14274. this._cursor = i;
  14275. // Render temporary displayables.
  14276. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14277. var displayable = this._temporaryDisplayables[i];
  14278. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14279. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14280. displayable.afterBrush && displayable.afterBrush(ctx);
  14281. }
  14282. this._temporaryDisplayables = [];
  14283. this.notClear = true;
  14284. };
  14285. var m = [];
  14286. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14287. if (!this._rect) {
  14288. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14289. for (var i = 0; i < this._displayables.length; i++) {
  14290. var displayable = this._displayables[i];
  14291. var childRect = displayable.getBoundingRect().clone();
  14292. if (displayable.needLocalTransform()) {
  14293. childRect.applyTransform(displayable.getLocalTransform(m));
  14294. }
  14295. rect.union(childRect);
  14296. }
  14297. this._rect = rect;
  14298. }
  14299. return this._rect;
  14300. };
  14301. IncrementalDisplayble.prototype.contain = function (x, y) {
  14302. var localPos = this.transformCoordToLocal(x, y);
  14303. var rect = this.getBoundingRect();
  14304. if (rect.contain(localPos[0], localPos[1])) {
  14305. for (var i = 0; i < this._displayables.length; i++) {
  14306. var displayable = this._displayables[i];
  14307. if (displayable.contain(x, y)) {
  14308. return true;
  14309. }
  14310. }
  14311. }
  14312. return false;
  14313. };
  14314. inherits(IncrementalDisplayble, Displayable);
  14315. /*
  14316. * Licensed to the Apache Software Foundation (ASF) under one
  14317. * or more contributor license agreements. See the NOTICE file
  14318. * distributed with this work for additional information
  14319. * regarding copyright ownership. The ASF licenses this file
  14320. * to you under the Apache License, Version 2.0 (the
  14321. * "License"); you may not use this file except in compliance
  14322. * with the License. You may obtain a copy of the License at
  14323. *
  14324. * http://www.apache.org/licenses/LICENSE-2.0
  14325. *
  14326. * Unless required by applicable law or agreed to in writing,
  14327. * software distributed under the License is distributed on an
  14328. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14329. * KIND, either express or implied. See the License for the
  14330. * specific language governing permissions and limitations
  14331. * under the License.
  14332. */
  14333. var round = Math.round;
  14334. var mathMax$1 = Math.max;
  14335. var mathMin$1 = Math.min;
  14336. var EMPTY_OBJ = {};
  14337. var Z2_EMPHASIS_LIFT = 1;
  14338. /**
  14339. * Extend shape with parameters
  14340. */
  14341. function extendShape(opts) {
  14342. return Path.extend(opts);
  14343. }
  14344. /**
  14345. * Extend path
  14346. */
  14347. function extendPath(pathData, opts) {
  14348. return extendFromString(pathData, opts);
  14349. }
  14350. /**
  14351. * Create a path element from path data string
  14352. * @param {string} pathData
  14353. * @param {Object} opts
  14354. * @param {module:zrender/core/BoundingRect} rect
  14355. * @param {string} [layout=cover] 'center' or 'cover'
  14356. */
  14357. function makePath(pathData, opts, rect, layout) {
  14358. var path = createFromString(pathData, opts);
  14359. if (rect) {
  14360. if (layout === 'center') {
  14361. rect = centerGraphic(rect, path.getBoundingRect());
  14362. }
  14363. resizePath(path, rect);
  14364. }
  14365. return path;
  14366. }
  14367. /**
  14368. * Create a image element from image url
  14369. * @param {string} imageUrl image url
  14370. * @param {Object} opts options
  14371. * @param {module:zrender/core/BoundingRect} rect constrain rect
  14372. * @param {string} [layout=cover] 'center' or 'cover'
  14373. */
  14374. function makeImage(imageUrl, rect, layout) {
  14375. var path = new ZImage({
  14376. style: {
  14377. image: imageUrl,
  14378. x: rect.x,
  14379. y: rect.y,
  14380. width: rect.width,
  14381. height: rect.height
  14382. },
  14383. onload: function (img) {
  14384. if (layout === 'center') {
  14385. var boundingRect = {
  14386. width: img.width,
  14387. height: img.height
  14388. };
  14389. path.setStyle(centerGraphic(rect, boundingRect));
  14390. }
  14391. }
  14392. });
  14393. return path;
  14394. }
  14395. /**
  14396. * Get position of centered element in bounding box.
  14397. *
  14398. * @param {Object} rect element local bounding box
  14399. * @param {Object} boundingRect constraint bounding box
  14400. * @return {Object} element position containing x, y, width, and height
  14401. */
  14402. function centerGraphic(rect, boundingRect) {
  14403. // Set rect to center, keep width / height ratio.
  14404. var aspect = boundingRect.width / boundingRect.height;
  14405. var width = rect.height * aspect;
  14406. var height;
  14407. if (width <= rect.width) {
  14408. height = rect.height;
  14409. }
  14410. else {
  14411. width = rect.width;
  14412. height = width / aspect;
  14413. }
  14414. var cx = rect.x + rect.width / 2;
  14415. var cy = rect.y + rect.height / 2;
  14416. return {
  14417. x: cx - width / 2,
  14418. y: cy - height / 2,
  14419. width: width,
  14420. height: height
  14421. };
  14422. }
  14423. var mergePath = mergePath$1;
  14424. /**
  14425. * Resize a path to fit the rect
  14426. * @param {module:zrender/graphic/Path} path
  14427. * @param {Object} rect
  14428. */
  14429. function resizePath(path, rect) {
  14430. if (!path.applyTransform) {
  14431. return;
  14432. }
  14433. var pathRect = path.getBoundingRect();
  14434. var m = pathRect.calculateTransform(rect);
  14435. path.applyTransform(m);
  14436. }
  14437. /**
  14438. * Sub pixel optimize line for canvas
  14439. *
  14440. * @param {Object} param
  14441. * @param {Object} [param.shape]
  14442. * @param {number} [param.shape.x1]
  14443. * @param {number} [param.shape.y1]
  14444. * @param {number} [param.shape.x2]
  14445. * @param {number} [param.shape.y2]
  14446. * @param {Object} [param.style]
  14447. * @param {number} [param.style.lineWidth]
  14448. * @return {Object} Modified param
  14449. */
  14450. function subPixelOptimizeLine(param) {
  14451. var shape = param.shape;
  14452. var lineWidth = param.style.lineWidth;
  14453. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  14454. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  14455. }
  14456. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  14457. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  14458. }
  14459. return param;
  14460. }
  14461. /**
  14462. * Sub pixel optimize rect for canvas
  14463. *
  14464. * @param {Object} param
  14465. * @param {Object} [param.shape]
  14466. * @param {number} [param.shape.x]
  14467. * @param {number} [param.shape.y]
  14468. * @param {number} [param.shape.width]
  14469. * @param {number} [param.shape.height]
  14470. * @param {Object} [param.style]
  14471. * @param {number} [param.style.lineWidth]
  14472. * @return {Object} Modified param
  14473. */
  14474. function subPixelOptimizeRect(param) {
  14475. var shape = param.shape;
  14476. var lineWidth = param.style.lineWidth;
  14477. var originX = shape.x;
  14478. var originY = shape.y;
  14479. var originWidth = shape.width;
  14480. var originHeight = shape.height;
  14481. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  14482. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  14483. shape.width = Math.max(
  14484. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  14485. originWidth === 0 ? 0 : 1
  14486. );
  14487. shape.height = Math.max(
  14488. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  14489. originHeight === 0 ? 0 : 1
  14490. );
  14491. return param;
  14492. }
  14493. /**
  14494. * Sub pixel optimize for canvas
  14495. *
  14496. * @param {number} position Coordinate, such as x, y
  14497. * @param {number} lineWidth Should be nonnegative integer.
  14498. * @param {boolean=} positiveOrNegative Default false (negative).
  14499. * @return {number} Optimized position.
  14500. */
  14501. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  14502. // Assure that (position + lineWidth / 2) is near integer edge,
  14503. // otherwise line will be fuzzy in canvas.
  14504. var doubledPosition = round(position * 2);
  14505. return (doubledPosition + round(lineWidth)) % 2 === 0
  14506. ? doubledPosition / 2
  14507. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14508. }
  14509. function hasFillOrStroke(fillOrStroke) {
  14510. return fillOrStroke != null && fillOrStroke !== 'none';
  14511. }
  14512. // Most lifted color are duplicated.
  14513. var liftedColorMap = createHashMap();
  14514. var liftedColorCount = 0;
  14515. function liftColor(color) {
  14516. if (typeof color !== 'string') {
  14517. return color;
  14518. }
  14519. var liftedColor = liftedColorMap.get(color);
  14520. if (!liftedColor) {
  14521. liftedColor = lift(color, -0.1);
  14522. if (liftedColorCount < 10000) {
  14523. liftedColorMap.set(color, liftedColor);
  14524. liftedColorCount++;
  14525. }
  14526. }
  14527. return liftedColor;
  14528. }
  14529. function cacheElementStl(el) {
  14530. if (!el.__hoverStlDirty) {
  14531. return;
  14532. }
  14533. el.__hoverStlDirty = false;
  14534. var hoverStyle = el.__hoverStl;
  14535. if (!hoverStyle) {
  14536. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  14537. return;
  14538. }
  14539. var normalStyle = el.__cachedNormalStl = {};
  14540. el.__cachedNormalZ2 = el.z2;
  14541. var elStyle = el.style;
  14542. for (var name in hoverStyle) {
  14543. // See comment in `doSingleEnterHover`.
  14544. if (hoverStyle[name] != null) {
  14545. normalStyle[name] = elStyle[name];
  14546. }
  14547. }
  14548. // Always cache fill and stroke to normalStyle for lifting color.
  14549. normalStyle.fill = elStyle.fill;
  14550. normalStyle.stroke = elStyle.stroke;
  14551. }
  14552. function doSingleEnterHover(el) {
  14553. var hoverStl = el.__hoverStl;
  14554. if (!hoverStl || el.__highlighted) {
  14555. return;
  14556. }
  14557. var useHoverLayer = el.useHoverLayer;
  14558. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  14559. var zr = el.__zr;
  14560. if (!zr && useHoverLayer) {
  14561. return;
  14562. }
  14563. var elTarget = el;
  14564. var targetStyle = el.style;
  14565. if (useHoverLayer) {
  14566. elTarget = zr.addHover(el);
  14567. targetStyle = elTarget.style;
  14568. }
  14569. rollbackDefaultTextStyle(targetStyle);
  14570. if (!useHoverLayer) {
  14571. cacheElementStl(elTarget);
  14572. }
  14573. // styles can be:
  14574. // {
  14575. // label: {
  14576. // show: false,
  14577. // position: 'outside',
  14578. // fontSize: 18
  14579. // },
  14580. // emphasis: {
  14581. // label: {
  14582. // show: true
  14583. // }
  14584. // }
  14585. // },
  14586. // where properties of `emphasis` may not appear in `normal`. We previously use
  14587. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14588. // But consider rich text and setOption in merge mode, it is impossible to cover
  14589. // all properties in merge. So we use merge mode when setting style here, where
  14590. // only properties that is not `null/undefined` can be set. The disadventage:
  14591. // null/undefined can not be used to remove style any more in `emphasis`.
  14592. targetStyle.extendFrom(hoverStl);
  14593. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  14594. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  14595. applyDefaultTextStyle(targetStyle);
  14596. if (!useHoverLayer) {
  14597. el.dirty(false);
  14598. el.z2 += Z2_EMPHASIS_LIFT;
  14599. }
  14600. }
  14601. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  14602. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  14603. targetStyle[prop] = liftColor(targetStyle[prop]);
  14604. }
  14605. }
  14606. function doSingleLeaveHover(el) {
  14607. var highlighted = el.__highlighted;
  14608. if (!highlighted) {
  14609. return;
  14610. }
  14611. el.__highlighted = false;
  14612. if (highlighted === 'layer') {
  14613. el.__zr && el.__zr.removeHover(el);
  14614. }
  14615. else if (highlighted) {
  14616. var style = el.style;
  14617. var normalStl = el.__cachedNormalStl;
  14618. if (normalStl) {
  14619. rollbackDefaultTextStyle(style);
  14620. // Consider null/undefined value, should use
  14621. // `setStyle` but not `extendFrom(stl, true)`.
  14622. el.setStyle(normalStl);
  14623. applyDefaultTextStyle(style);
  14624. }
  14625. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  14626. // when `el` is on emphasis state. So here by comparing with 1, we try
  14627. // hard to make the bug case rare.
  14628. var normalZ2 = el.__cachedNormalZ2;
  14629. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  14630. el.z2 = normalZ2;
  14631. }
  14632. }
  14633. }
  14634. function traverseCall(el, method) {
  14635. el.isGroup
  14636. ? el.traverse(function (child) {
  14637. !child.isGroup && method(child);
  14638. })
  14639. : method(el);
  14640. }
  14641. /**
  14642. * Set hover style (namely "emphasis style") of element, based on the current
  14643. * style of the given `el`.
  14644. * This method should be called after all of the normal styles have been adopted
  14645. * to the `el`. See the reason on `setHoverStyle`.
  14646. *
  14647. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  14648. * @param {Object|boolean} [hoverStl] The specified hover style.
  14649. * If set as `false`, disable the hover style.
  14650. * Similarly, The `el.hoverStyle` can alse be set
  14651. * as `false` to disable the hover style.
  14652. * Otherwise, use the default hover style if not provided.
  14653. * @param {Object} [opt]
  14654. * @param {boolean} [opt.hoverSilentOnTouch=false] See `graphic.setAsHoverStyleTrigger`
  14655. */
  14656. function setElementHoverStyle(el, hoverStl) {
  14657. // For performance consideration, it might be better to make the "hover style" only the
  14658. // difference properties from the "normal style", but not a entire copy of all styles.
  14659. hoverStl = el.__hoverStl = hoverStl !== false && (hoverStl || {});
  14660. el.__hoverStlDirty = true;
  14661. // FIXME
  14662. // It is not completely right to save "normal"/"emphasis" flag on elements.
  14663. // It probably should be saved on `data` of series. Consider the cases:
  14664. // (1) A highlighted elements are moved out of the view port and re-enter
  14665. // again by dataZoom.
  14666. // (2) call `setOption` and replace elements totally when they are highlighted.
  14667. if (el.__highlighted) {
  14668. // Consider the case:
  14669. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  14670. // should be adapted to the `el`. Notice here new "normal styles" should have
  14671. // been set outside and the cached "normal style" is out of date.
  14672. el.__cachedNormalStl = null;
  14673. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  14674. // of this method. In most cases, `z2` is not set and hover style should be able
  14675. // to rollback. Of course, that would bring bug, but only in a rare case, see
  14676. // `doSingleLeaveHover` for details.
  14677. doSingleLeaveHover(el);
  14678. doSingleEnterHover(el);
  14679. }
  14680. }
  14681. /**
  14682. * Emphasis (called by API) has higher priority than `mouseover`.
  14683. * When element has been called to be entered emphasis, mouse over
  14684. * should not trigger the highlight effect (for example, animation
  14685. * scale) again, and `mouseout` should not downplay the highlight
  14686. * effect. So the listener of `mouseover` and `mouseout` should
  14687. * check `isInEmphasis`.
  14688. *
  14689. * @param {module:zrender/Element} el
  14690. * @return {boolean}
  14691. */
  14692. function isInEmphasis(el) {
  14693. return el && el.__isEmphasisEntered;
  14694. }
  14695. function onElementMouseOver(e) {
  14696. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14697. return;
  14698. }
  14699. // Only if element is not in emphasis status
  14700. !this.__isEmphasisEntered && traverseCall(this, doSingleEnterHover);
  14701. }
  14702. function onElementMouseOut(e) {
  14703. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14704. return;
  14705. }
  14706. // Only if element is not in emphasis status
  14707. !this.__isEmphasisEntered && traverseCall(this, doSingleLeaveHover);
  14708. }
  14709. function enterEmphasis() {
  14710. this.__isEmphasisEntered = true;
  14711. traverseCall(this, doSingleEnterHover);
  14712. }
  14713. function leaveEmphasis() {
  14714. this.__isEmphasisEntered = false;
  14715. traverseCall(this, doSingleLeaveHover);
  14716. }
  14717. /**
  14718. * Set hover style (namely "emphasis style") of element,
  14719. * based on the current style of the given `el`.
  14720. *
  14721. * (1)
  14722. * **CONSTRAINTS** for this method:
  14723. * <A> This method MUST be called after all of the normal styles having been adopted
  14724. * to the `el`.
  14725. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  14726. * "normal style" having been set to the el.
  14727. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  14728. * a default hover style).
  14729. *
  14730. * The reason: this method treat the current style of the `el` as the "normal style"
  14731. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  14732. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  14733. * logic, where the el should shift from the original emphasis style to the new
  14734. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  14735. *
  14736. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  14737. * not found a better solution yet to fit the backward compatibility, performance and
  14738. * the current programming style.
  14739. *
  14740. * (2)
  14741. * Call the method for a "root" element once. Do not call it for each descendants.
  14742. * If the descendants elemenets of a group has itself hover style different from the
  14743. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  14744. * not call this method for them.
  14745. *
  14746. * @param {module:zrender/Element} el
  14747. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  14748. * @param {Object} [opt]
  14749. * @param {boolean} [opt.hoverSilentOnTouch=false] See `graphic.setAsHoverStyleTrigger`.
  14750. */
  14751. function setHoverStyle(el, hoverStyle, opt) {
  14752. el.isGroup
  14753. ? el.traverse(function (child) {
  14754. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  14755. // Often used when item group has a label element and it's hoverStyle is different
  14756. !child.isGroup && setElementHoverStyle(child, child.hoverStyle || hoverStyle);
  14757. })
  14758. : setElementHoverStyle(el, el.hoverStyle || hoverStyle);
  14759. setAsHoverStyleTrigger(el, opt);
  14760. }
  14761. /**
  14762. * @param {Object|boolean} [opt] If `false`, means disable trigger.
  14763. * @param {boolean} [opt.hoverSilentOnTouch=false]
  14764. * In touch device, mouseover event will be trigger on touchstart event
  14765. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14766. * conveniently use hoverStyle when tap on touch screen without additional
  14767. * code for compatibility.
  14768. * But if the chart/component has select feature, which usually also use
  14769. * hoverStyle, there might be conflict between 'select-highlight' and
  14770. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14771. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14772. * on touch device.
  14773. */
  14774. function setAsHoverStyleTrigger(el, opt) {
  14775. var disable = opt === false;
  14776. el.__hoverSilentOnTouch = opt != null && opt.hoverSilentOnTouch;
  14777. // Simple optimize, since this method might be
  14778. // called for each elements of a group in some cases.
  14779. if (!disable || el.__hoverStyleTrigger) {
  14780. var method = disable ? 'off' : 'on';
  14781. // Duplicated function will be auto-ignored, see Eventful.js.
  14782. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  14783. // Emphasis, normal can be triggered manually
  14784. el[method]('emphasis', enterEmphasis)[method]('normal', leaveEmphasis);
  14785. el.__hoverStyleTrigger = !disable;
  14786. }
  14787. }
  14788. /**
  14789. * See more info in `setTextStyleCommon`.
  14790. * @param {Object|module:zrender/graphic/Style} normalStyle
  14791. * @param {Object} emphasisStyle
  14792. * @param {module:echarts/model/Model} normalModel
  14793. * @param {module:echarts/model/Model} emphasisModel
  14794. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14795. * @param {string|Function} [opt.defaultText]
  14796. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14797. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14798. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14799. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14800. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14801. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14802. * @param {Object} [normalSpecified]
  14803. * @param {Object} [emphasisSpecified]
  14804. */
  14805. function setLabelStyle(
  14806. normalStyle, emphasisStyle,
  14807. normalModel, emphasisModel,
  14808. opt,
  14809. normalSpecified, emphasisSpecified
  14810. ) {
  14811. opt = opt || EMPTY_OBJ;
  14812. var labelFetcher = opt.labelFetcher;
  14813. var labelDataIndex = opt.labelDataIndex;
  14814. var labelDimIndex = opt.labelDimIndex;
  14815. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14816. // is not supported util someone requests.
  14817. var showNormal = normalModel.getShallow('show');
  14818. var showEmphasis = emphasisModel.getShallow('show');
  14819. // Consider performance, only fetch label when necessary.
  14820. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14821. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14822. var baseText;
  14823. if (showNormal || showEmphasis) {
  14824. if (labelFetcher) {
  14825. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  14826. }
  14827. if (baseText == null) {
  14828. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14829. }
  14830. }
  14831. var normalStyleText = showNormal ? baseText : null;
  14832. var emphasisStyleText = showEmphasis
  14833. ? retrieve2(
  14834. labelFetcher
  14835. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14836. : null,
  14837. baseText
  14838. )
  14839. : null;
  14840. // Optimize: If style.text is null, text will not be drawn.
  14841. if (normalStyleText != null || emphasisStyleText != null) {
  14842. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14843. // values have to be set on `normalStyle`.
  14844. // If we set default values on `emphasisStyle`, consider case:
  14845. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14846. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14847. // Then the 'red' will not work on emphasis.
  14848. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14849. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14850. }
  14851. normalStyle.text = normalStyleText;
  14852. emphasisStyle.text = emphasisStyleText;
  14853. }
  14854. /**
  14855. * Set basic textStyle properties.
  14856. * See more info in `setTextStyleCommon`.
  14857. * @param {Object|module:zrender/graphic/Style} textStyle
  14858. * @param {module:echarts/model/Model} model
  14859. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14860. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14861. * @param {boolean} [isEmphasis]
  14862. */
  14863. function setTextStyle(
  14864. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14865. ) {
  14866. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14867. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14868. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14869. return textStyle;
  14870. }
  14871. /**
  14872. * Set text option in the style.
  14873. * See more info in `setTextStyleCommon`.
  14874. * @deprecated
  14875. * @param {Object} textStyle
  14876. * @param {module:echarts/model/Model} labelModel
  14877. * @param {string|boolean} defaultColor Default text color.
  14878. * If set as false, it will be processed as a emphasis style.
  14879. */
  14880. function setText(textStyle, labelModel, defaultColor) {
  14881. var opt = {isRectText: true};
  14882. var isEmphasis;
  14883. if (defaultColor === false) {
  14884. isEmphasis = true;
  14885. }
  14886. else {
  14887. // Support setting color as 'auto' to get visual color.
  14888. opt.autoColor = defaultColor;
  14889. }
  14890. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14891. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14892. }
  14893. /**
  14894. * The uniform entry of set text style, that is, retrieve style definitions
  14895. * from `model` and set to `textStyle` object.
  14896. *
  14897. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14898. * properties will be set. (Consider the states of normal and emphasis and
  14899. * default value can be adopted, merge would make the logic too complicated
  14900. * to manage.)
  14901. *
  14902. * The `textStyle` object can either be a plain object or an instance of
  14903. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  14904. * After this mothod called, the `textStyle` object can then be used in
  14905. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  14906. *
  14907. * Default value will be adopted and `insideRollbackOpt` will be created.
  14908. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  14909. *
  14910. * opt: {
  14911. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14912. * isRectText: boolean,
  14913. * autoColor: string, specify a color when color is 'auto',
  14914. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14915. * If autoColor specified, it is used as default textFill.
  14916. * useInsideStyle:
  14917. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14918. * if `textFill` is not specified.
  14919. * `false`: Do not use inside style.
  14920. * `null/undefined`: use inside style if `isRectText` is true and
  14921. * `textFill` is not specified and textPosition contains `'inside'`.
  14922. * forceRich: boolean
  14923. * }
  14924. */
  14925. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14926. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14927. opt = opt || EMPTY_OBJ;
  14928. if (opt.isRectText) {
  14929. var textPosition = textStyleModel.getShallow('position')
  14930. || (isEmphasis ? null : 'inside');
  14931. // 'outside' is not a valid zr textPostion value, but used
  14932. // in bar series, and magric type should be considered.
  14933. textPosition === 'outside' && (textPosition = 'top');
  14934. textStyle.textPosition = textPosition;
  14935. textStyle.textOffset = textStyleModel.getShallow('offset');
  14936. var labelRotate = textStyleModel.getShallow('rotate');
  14937. labelRotate != null && (labelRotate *= Math.PI / 180);
  14938. textStyle.textRotation = labelRotate;
  14939. textStyle.textDistance = retrieve2(
  14940. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14941. );
  14942. }
  14943. var ecModel = textStyleModel.ecModel;
  14944. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14945. // Consider case:
  14946. // {
  14947. // data: [{
  14948. // value: 12,
  14949. // label: {
  14950. // rich: {
  14951. // // no 'a' here but using parent 'a'.
  14952. // }
  14953. // }
  14954. // }],
  14955. // rich: {
  14956. // a: { ... }
  14957. // }
  14958. // }
  14959. var richItemNames = getRichItemNames(textStyleModel);
  14960. var richResult;
  14961. if (richItemNames) {
  14962. richResult = {};
  14963. for (var name in richItemNames) {
  14964. if (richItemNames.hasOwnProperty(name)) {
  14965. // Cascade is supported in rich.
  14966. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14967. // In rich, never `disableBox`.
  14968. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14969. }
  14970. }
  14971. }
  14972. textStyle.rich = richResult;
  14973. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14974. if (opt.forceRich && !opt.textStyle) {
  14975. opt.textStyle = {};
  14976. }
  14977. return textStyle;
  14978. }
  14979. // Consider case:
  14980. // {
  14981. // data: [{
  14982. // value: 12,
  14983. // label: {
  14984. // rich: {
  14985. // // no 'a' here but using parent 'a'.
  14986. // }
  14987. // }
  14988. // }],
  14989. // rich: {
  14990. // a: { ... }
  14991. // }
  14992. // }
  14993. function getRichItemNames(textStyleModel) {
  14994. // Use object to remove duplicated names.
  14995. var richItemNameMap;
  14996. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14997. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14998. if (rich) {
  14999. richItemNameMap = richItemNameMap || {};
  15000. for (var name in rich) {
  15001. if (rich.hasOwnProperty(name)) {
  15002. richItemNameMap[name] = 1;
  15003. }
  15004. }
  15005. }
  15006. textStyleModel = textStyleModel.parentModel;
  15007. }
  15008. return richItemNameMap;
  15009. }
  15010. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  15011. // In merge mode, default value should not be given.
  15012. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  15013. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  15014. || globalTextStyle.color;
  15015. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  15016. || globalTextStyle.textBorderColor;
  15017. textStyle.textStrokeWidth = retrieve2(
  15018. textStyleModel.getShallow('textBorderWidth'),
  15019. globalTextStyle.textBorderWidth
  15020. );
  15021. // Save original textPosition, because style.textPosition will be repalced by
  15022. // real location (like [10, 30]) in zrender.
  15023. textStyle.insideRawTextPosition = textStyle.textPosition;
  15024. if (!isEmphasis) {
  15025. if (isBlock) {
  15026. textStyle.insideRollbackOpt = opt;
  15027. applyDefaultTextStyle(textStyle);
  15028. }
  15029. // Set default finally.
  15030. if (textStyle.textFill == null) {
  15031. textStyle.textFill = opt.autoColor;
  15032. }
  15033. }
  15034. // Do not use `getFont` here, because merge should be supported, where
  15035. // part of these properties may be changed in emphasis style, and the
  15036. // others should remain their original value got from normal style.
  15037. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  15038. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  15039. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  15040. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  15041. textStyle.textAlign = textStyleModel.getShallow('align');
  15042. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  15043. || textStyleModel.getShallow('baseline');
  15044. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  15045. textStyle.textWidth = textStyleModel.getShallow('width');
  15046. textStyle.textHeight = textStyleModel.getShallow('height');
  15047. textStyle.textTag = textStyleModel.getShallow('tag');
  15048. if (!isBlock || !opt.disableBox) {
  15049. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  15050. textStyle.textPadding = textStyleModel.getShallow('padding');
  15051. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  15052. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  15053. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  15054. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  15055. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  15056. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  15057. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  15058. }
  15059. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  15060. || globalTextStyle.textShadowColor;
  15061. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  15062. || globalTextStyle.textShadowBlur;
  15063. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  15064. || globalTextStyle.textShadowOffsetX;
  15065. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  15066. || globalTextStyle.textShadowOffsetY;
  15067. }
  15068. function getAutoColor(color, opt) {
  15069. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  15070. }
  15071. /**
  15072. * Give some default value to the input `textStyle` object, based on the current settings
  15073. * in this `textStyle` object.
  15074. *
  15075. * The Scenario:
  15076. * when text position is `inside` and `textFill` is not specified, we show
  15077. * text border by default for better view. But it should be considered that text position
  15078. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  15079. * restore the style.
  15080. *
  15081. * Usage (& NOTICE):
  15082. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  15083. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  15084. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  15085. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  15086. * does, `rollbackDefaultTextStyle` is not needed to be called).
  15087. */
  15088. function applyDefaultTextStyle(textStyle) {
  15089. var opt = textStyle.insideRollbackOpt;
  15090. // Only `insideRollbackOpt` created (in `setTextStyleCommon`),
  15091. // applyDefaultTextStyle works.
  15092. if (!opt || textStyle.textFill != null) {
  15093. return;
  15094. }
  15095. var useInsideStyle = opt.useInsideStyle;
  15096. var textPosition = textStyle.insideRawTextPosition;
  15097. var insideRollback;
  15098. var autoColor = opt.autoColor;
  15099. if (useInsideStyle !== false
  15100. && (useInsideStyle === true
  15101. || (opt.isRectText
  15102. && textPosition
  15103. // textPosition can be [10, 30]
  15104. && typeof textPosition === 'string'
  15105. && textPosition.indexOf('inside') >= 0
  15106. )
  15107. )
  15108. ) {
  15109. insideRollback = {
  15110. textFill: null,
  15111. textStroke: textStyle.textStroke,
  15112. textStrokeWidth: textStyle.textStrokeWidth
  15113. };
  15114. textStyle.textFill = '#fff';
  15115. // Consider text with #fff overflow its container.
  15116. if (textStyle.textStroke == null) {
  15117. textStyle.textStroke = autoColor;
  15118. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  15119. }
  15120. }
  15121. else if (autoColor != null) {
  15122. insideRollback = {textFill: null};
  15123. textStyle.textFill = autoColor;
  15124. }
  15125. // Always set `insideRollback`, for clearing previous.
  15126. if (insideRollback) {
  15127. textStyle.insideRollback = insideRollback;
  15128. }
  15129. }
  15130. /**
  15131. * Consider the case: in a scatter,
  15132. * label: {
  15133. * normal: {position: 'inside'},
  15134. * emphasis: {position: 'top'}
  15135. * }
  15136. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  15137. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  15138. * should be retured to 'autoColor', but not keep '#fff'.
  15139. */
  15140. function rollbackDefaultTextStyle(style) {
  15141. var insideRollback = style.insideRollback;
  15142. if (insideRollback) {
  15143. style.textFill = insideRollback.textFill;
  15144. style.textStroke = insideRollback.textStroke;
  15145. style.textStrokeWidth = insideRollback.textStrokeWidth;
  15146. style.insideRollback = null;
  15147. }
  15148. }
  15149. function getFont(opt, ecModel) {
  15150. // ecModel or default text style model.
  15151. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  15152. return trim([
  15153. // FIXME in node-canvas fontWeight is before fontStyle
  15154. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  15155. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  15156. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  15157. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  15158. ].join(' '));
  15159. }
  15160. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  15161. if (typeof dataIndex === 'function') {
  15162. cb = dataIndex;
  15163. dataIndex = null;
  15164. }
  15165. // Do not check 'animation' property directly here. Consider this case:
  15166. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  15167. // but its parent model (`seriesModel`) does.
  15168. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  15169. if (animationEnabled) {
  15170. var postfix = isUpdate ? 'Update' : '';
  15171. var duration = animatableModel.getShallow('animationDuration' + postfix);
  15172. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  15173. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  15174. if (typeof animationDelay === 'function') {
  15175. animationDelay = animationDelay(
  15176. dataIndex,
  15177. animatableModel.getAnimationDelayParams
  15178. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  15179. : null
  15180. );
  15181. }
  15182. if (typeof duration === 'function') {
  15183. duration = duration(dataIndex);
  15184. }
  15185. duration > 0
  15186. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  15187. : (el.stopAnimation(), el.attr(props), cb && cb());
  15188. }
  15189. else {
  15190. el.stopAnimation();
  15191. el.attr(props);
  15192. cb && cb();
  15193. }
  15194. }
  15195. /**
  15196. * Update graphic element properties with or without animation according to the
  15197. * configuration in series.
  15198. *
  15199. * Caution: this method will stop previous animation.
  15200. * So if do not use this method to one element twice before
  15201. * animation starts, unless you know what you are doing.
  15202. *
  15203. * @param {module:zrender/Element} el
  15204. * @param {Object} props
  15205. * @param {module:echarts/model/Model} [animatableModel]
  15206. * @param {number} [dataIndex]
  15207. * @param {Function} [cb]
  15208. * @example
  15209. * graphic.updateProps(el, {
  15210. * position: [100, 100]
  15211. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  15212. * // Or
  15213. * graphic.updateProps(el, {
  15214. * position: [100, 100]
  15215. * }, seriesModel, function () { console.log('Animation done!'); });
  15216. */
  15217. function updateProps(el, props, animatableModel, dataIndex, cb) {
  15218. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  15219. }
  15220. /**
  15221. * Init graphic element properties with or without animation according to the
  15222. * configuration in series.
  15223. *
  15224. * Caution: this method will stop previous animation.
  15225. * So if do not use this method to one element twice before
  15226. * animation starts, unless you know what you are doing.
  15227. *
  15228. * @param {module:zrender/Element} el
  15229. * @param {Object} props
  15230. * @param {module:echarts/model/Model} [animatableModel]
  15231. * @param {number} [dataIndex]
  15232. * @param {Function} cb
  15233. */
  15234. function initProps(el, props, animatableModel, dataIndex, cb) {
  15235. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  15236. }
  15237. /**
  15238. * Get transform matrix of target (param target),
  15239. * in coordinate of its ancestor (param ancestor)
  15240. *
  15241. * @param {module:zrender/mixin/Transformable} target
  15242. * @param {module:zrender/mixin/Transformable} [ancestor]
  15243. */
  15244. function getTransform(target, ancestor) {
  15245. var mat = identity([]);
  15246. while (target && target !== ancestor) {
  15247. mul$1(mat, target.getLocalTransform(), mat);
  15248. target = target.parent;
  15249. }
  15250. return mat;
  15251. }
  15252. /**
  15253. * Apply transform to an vertex.
  15254. * @param {Array.<number>} target [x, y]
  15255. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  15256. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  15257. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  15258. * @param {boolean=} invert Whether use invert matrix.
  15259. * @return {Array.<number>} [x, y]
  15260. */
  15261. function applyTransform$1(target, transform, invert$$1) {
  15262. if (transform && !isArrayLike(transform)) {
  15263. transform = Transformable.getLocalTransform(transform);
  15264. }
  15265. if (invert$$1) {
  15266. transform = invert([], transform);
  15267. }
  15268. return applyTransform([], target, transform);
  15269. }
  15270. /**
  15271. * @param {string} direction 'left' 'right' 'top' 'bottom'
  15272. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  15273. * @param {boolean=} invert Whether use invert matrix.
  15274. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  15275. */
  15276. function transformDirection(direction, transform, invert$$1) {
  15277. // Pick a base, ensure that transform result will not be (0, 0).
  15278. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  15279. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  15280. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  15281. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  15282. var vertex = [
  15283. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  15284. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  15285. ];
  15286. vertex = applyTransform$1(vertex, transform, invert$$1);
  15287. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  15288. ? (vertex[0] > 0 ? 'right' : 'left')
  15289. : (vertex[1] > 0 ? 'bottom' : 'top');
  15290. }
  15291. /**
  15292. * Apply group transition animation from g1 to g2.
  15293. * If no animatableModel, no animation.
  15294. */
  15295. function groupTransition(g1, g2, animatableModel, cb) {
  15296. if (!g1 || !g2) {
  15297. return;
  15298. }
  15299. function getElMap(g) {
  15300. var elMap = {};
  15301. g.traverse(function (el) {
  15302. if (!el.isGroup && el.anid) {
  15303. elMap[el.anid] = el;
  15304. }
  15305. });
  15306. return elMap;
  15307. }
  15308. function getAnimatableProps(el) {
  15309. var obj = {
  15310. position: clone$1(el.position),
  15311. rotation: el.rotation
  15312. };
  15313. if (el.shape) {
  15314. obj.shape = extend({}, el.shape);
  15315. }
  15316. return obj;
  15317. }
  15318. var elMap1 = getElMap(g1);
  15319. g2.traverse(function (el) {
  15320. if (!el.isGroup && el.anid) {
  15321. var oldEl = elMap1[el.anid];
  15322. if (oldEl) {
  15323. var newProp = getAnimatableProps(el);
  15324. el.attr(getAnimatableProps(oldEl));
  15325. updateProps(el, newProp, animatableModel, el.dataIndex);
  15326. }
  15327. // else {
  15328. // if (el.previousProps) {
  15329. // graphic.updateProps
  15330. // }
  15331. // }
  15332. }
  15333. });
  15334. }
  15335. /**
  15336. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  15337. * @param {Object} rect {x, y, width, height}
  15338. * @return {Array.<Array.<number>>} A new clipped points.
  15339. */
  15340. function clipPointsByRect(points, rect) {
  15341. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  15342. // and when element have border.
  15343. return map(points, function (point) {
  15344. var x = point[0];
  15345. x = mathMax$1(x, rect.x);
  15346. x = mathMin$1(x, rect.x + rect.width);
  15347. var y = point[1];
  15348. y = mathMax$1(y, rect.y);
  15349. y = mathMin$1(y, rect.y + rect.height);
  15350. return [x, y];
  15351. });
  15352. }
  15353. /**
  15354. * @param {Object} targetRect {x, y, width, height}
  15355. * @param {Object} rect {x, y, width, height}
  15356. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  15357. */
  15358. function clipRectByRect(targetRect, rect) {
  15359. var x = mathMax$1(targetRect.x, rect.x);
  15360. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  15361. var y = mathMax$1(targetRect.y, rect.y);
  15362. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  15363. // If the total rect is cliped, nothing, including the border,
  15364. // should be painted. So return undefined.
  15365. if (x2 >= x && y2 >= y) {
  15366. return {
  15367. x: x,
  15368. y: y,
  15369. width: x2 - x,
  15370. height: y2 - y
  15371. };
  15372. }
  15373. }
  15374. /**
  15375. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  15376. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  15377. * @param {Object} [rect] {x, y, width, height}
  15378. * @return {module:zrender/Element} Icon path or image element.
  15379. */
  15380. function createIcon(iconStr, opt, rect) {
  15381. opt = extend({rectHover: true}, opt);
  15382. var style = opt.style = {strokeNoScale: true};
  15383. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  15384. if (iconStr) {
  15385. return iconStr.indexOf('image://') === 0
  15386. ? (
  15387. style.image = iconStr.slice(8),
  15388. defaults(style, rect),
  15389. new ZImage(opt)
  15390. )
  15391. : (
  15392. makePath(
  15393. iconStr.replace('path://', ''),
  15394. opt,
  15395. rect,
  15396. 'center'
  15397. )
  15398. );
  15399. }
  15400. }
  15401. var graphic = (Object.freeze || Object)({
  15402. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  15403. extendShape: extendShape,
  15404. extendPath: extendPath,
  15405. makePath: makePath,
  15406. makeImage: makeImage,
  15407. mergePath: mergePath,
  15408. resizePath: resizePath,
  15409. subPixelOptimizeLine: subPixelOptimizeLine,
  15410. subPixelOptimizeRect: subPixelOptimizeRect,
  15411. subPixelOptimize: subPixelOptimize,
  15412. setElementHoverStyle: setElementHoverStyle,
  15413. isInEmphasis: isInEmphasis,
  15414. setHoverStyle: setHoverStyle,
  15415. setAsHoverStyleTrigger: setAsHoverStyleTrigger,
  15416. setLabelStyle: setLabelStyle,
  15417. setTextStyle: setTextStyle,
  15418. setText: setText,
  15419. getFont: getFont,
  15420. updateProps: updateProps,
  15421. initProps: initProps,
  15422. getTransform: getTransform,
  15423. applyTransform: applyTransform$1,
  15424. transformDirection: transformDirection,
  15425. groupTransition: groupTransition,
  15426. clipPointsByRect: clipPointsByRect,
  15427. clipRectByRect: clipRectByRect,
  15428. createIcon: createIcon,
  15429. Group: Group,
  15430. Image: ZImage,
  15431. Text: Text,
  15432. Circle: Circle,
  15433. Sector: Sector,
  15434. Ring: Ring,
  15435. Polygon: Polygon,
  15436. Polyline: Polyline,
  15437. Rect: Rect,
  15438. Line: Line,
  15439. BezierCurve: BezierCurve,
  15440. Arc: Arc,
  15441. IncrementalDisplayable: IncrementalDisplayble,
  15442. CompoundPath: CompoundPath,
  15443. LinearGradient: LinearGradient,
  15444. RadialGradient: RadialGradient,
  15445. BoundingRect: BoundingRect
  15446. });
  15447. /*
  15448. * Licensed to the Apache Software Foundation (ASF) under one
  15449. * or more contributor license agreements. See the NOTICE file
  15450. * distributed with this work for additional information
  15451. * regarding copyright ownership. The ASF licenses this file
  15452. * to you under the Apache License, Version 2.0 (the
  15453. * "License"); you may not use this file except in compliance
  15454. * with the License. You may obtain a copy of the License at
  15455. *
  15456. * http://www.apache.org/licenses/LICENSE-2.0
  15457. *
  15458. * Unless required by applicable law or agreed to in writing,
  15459. * software distributed under the License is distributed on an
  15460. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15461. * KIND, either express or implied. See the License for the
  15462. * specific language governing permissions and limitations
  15463. * under the License.
  15464. */
  15465. var PATH_COLOR = ['textStyle', 'color'];
  15466. var textStyleMixin = {
  15467. /**
  15468. * Get color property or get color from option.textStyle.color
  15469. * @param {boolean} [isEmphasis]
  15470. * @return {string}
  15471. */
  15472. getTextColor: function (isEmphasis) {
  15473. var ecModel = this.ecModel;
  15474. return this.getShallow('color')
  15475. || (
  15476. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  15477. );
  15478. },
  15479. /**
  15480. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15481. * @return {string}
  15482. */
  15483. getFont: function () {
  15484. return getFont({
  15485. fontStyle: this.getShallow('fontStyle'),
  15486. fontWeight: this.getShallow('fontWeight'),
  15487. fontSize: this.getShallow('fontSize'),
  15488. fontFamily: this.getShallow('fontFamily')
  15489. }, this.ecModel);
  15490. },
  15491. getTextRect: function (text) {
  15492. return getBoundingRect(
  15493. text,
  15494. this.getFont(),
  15495. this.getShallow('align'),
  15496. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  15497. this.getShallow('padding'),
  15498. this.getShallow('lineHeight'),
  15499. this.getShallow('rich'),
  15500. this.getShallow('truncateText')
  15501. );
  15502. }
  15503. };
  15504. /*
  15505. * Licensed to the Apache Software Foundation (ASF) under one
  15506. * or more contributor license agreements. See the NOTICE file
  15507. * distributed with this work for additional information
  15508. * regarding copyright ownership. The ASF licenses this file
  15509. * to you under the Apache License, Version 2.0 (the
  15510. * "License"); you may not use this file except in compliance
  15511. * with the License. You may obtain a copy of the License at
  15512. *
  15513. * http://www.apache.org/licenses/LICENSE-2.0
  15514. *
  15515. * Unless required by applicable law or agreed to in writing,
  15516. * software distributed under the License is distributed on an
  15517. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15518. * KIND, either express or implied. See the License for the
  15519. * specific language governing permissions and limitations
  15520. * under the License.
  15521. */
  15522. var getItemStyle = makeStyleMapper(
  15523. [
  15524. ['fill', 'color'],
  15525. ['stroke', 'borderColor'],
  15526. ['lineWidth', 'borderWidth'],
  15527. ['opacity'],
  15528. ['shadowBlur'],
  15529. ['shadowOffsetX'],
  15530. ['shadowOffsetY'],
  15531. ['shadowColor'],
  15532. ['textPosition'],
  15533. ['textAlign']
  15534. ]
  15535. );
  15536. var itemStyleMixin = {
  15537. getItemStyle: function (excludes, includes) {
  15538. var style = getItemStyle(this, excludes, includes);
  15539. var lineDash = this.getBorderLineDash();
  15540. lineDash && (style.lineDash = lineDash);
  15541. return style;
  15542. },
  15543. getBorderLineDash: function () {
  15544. var lineType = this.get('borderType');
  15545. return (lineType === 'solid' || lineType == null) ? null
  15546. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  15547. }
  15548. };
  15549. /*
  15550. * Licensed to the Apache Software Foundation (ASF) under one
  15551. * or more contributor license agreements. See the NOTICE file
  15552. * distributed with this work for additional information
  15553. * regarding copyright ownership. The ASF licenses this file
  15554. * to you under the Apache License, Version 2.0 (the
  15555. * "License"); you may not use this file except in compliance
  15556. * with the License. You may obtain a copy of the License at
  15557. *
  15558. * http://www.apache.org/licenses/LICENSE-2.0
  15559. *
  15560. * Unless required by applicable law or agreed to in writing,
  15561. * software distributed under the License is distributed on an
  15562. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15563. * KIND, either express or implied. See the License for the
  15564. * specific language governing permissions and limitations
  15565. * under the License.
  15566. */
  15567. /**
  15568. * @module echarts/model/Model
  15569. */
  15570. var mixin$1 = mixin;
  15571. var inner = makeInner();
  15572. /**
  15573. * @alias module:echarts/model/Model
  15574. * @constructor
  15575. * @param {Object} [option]
  15576. * @param {module:echarts/model/Model} [parentModel]
  15577. * @param {module:echarts/model/Global} [ecModel]
  15578. */
  15579. function Model(option, parentModel, ecModel) {
  15580. /**
  15581. * @type {module:echarts/model/Model}
  15582. * @readOnly
  15583. */
  15584. this.parentModel = parentModel;
  15585. /**
  15586. * @type {module:echarts/model/Global}
  15587. * @readOnly
  15588. */
  15589. this.ecModel = ecModel;
  15590. /**
  15591. * @type {Object}
  15592. * @protected
  15593. */
  15594. this.option = option;
  15595. // Simple optimization
  15596. // if (this.init) {
  15597. // if (arguments.length <= 4) {
  15598. // this.init(option, parentModel, ecModel, extraOpt);
  15599. // }
  15600. // else {
  15601. // this.init.apply(this, arguments);
  15602. // }
  15603. // }
  15604. }
  15605. Model.prototype = {
  15606. constructor: Model,
  15607. /**
  15608. * Model 的初始化函数
  15609. * @param {Object} option
  15610. */
  15611. init: null,
  15612. /**
  15613. * 从新的 Option merge
  15614. */
  15615. mergeOption: function (option) {
  15616. merge(this.option, option, true);
  15617. },
  15618. /**
  15619. * @param {string|Array.<string>} path
  15620. * @param {boolean} [ignoreParent=false]
  15621. * @return {*}
  15622. */
  15623. get: function (path, ignoreParent) {
  15624. if (path == null) {
  15625. return this.option;
  15626. }
  15627. return doGet(
  15628. this.option,
  15629. this.parsePath(path),
  15630. !ignoreParent && getParent(this, path)
  15631. );
  15632. },
  15633. /**
  15634. * @param {string} key
  15635. * @param {boolean} [ignoreParent=false]
  15636. * @return {*}
  15637. */
  15638. getShallow: function (key, ignoreParent) {
  15639. var option = this.option;
  15640. var val = option == null ? option : option[key];
  15641. var parentModel = !ignoreParent && getParent(this, key);
  15642. if (val == null && parentModel) {
  15643. val = parentModel.getShallow(key);
  15644. }
  15645. return val;
  15646. },
  15647. /**
  15648. * @param {string|Array.<string>} [path]
  15649. * @param {module:echarts/model/Model} [parentModel]
  15650. * @return {module:echarts/model/Model}
  15651. */
  15652. getModel: function (path, parentModel) {
  15653. var obj = path == null
  15654. ? this.option
  15655. : doGet(this.option, path = this.parsePath(path));
  15656. var thisParentModel;
  15657. parentModel = parentModel || (
  15658. (thisParentModel = getParent(this, path))
  15659. && thisParentModel.getModel(path)
  15660. );
  15661. return new Model(obj, parentModel, this.ecModel);
  15662. },
  15663. /**
  15664. * If model has option
  15665. */
  15666. isEmpty: function () {
  15667. return this.option == null;
  15668. },
  15669. restoreData: function () {},
  15670. // Pending
  15671. clone: function () {
  15672. var Ctor = this.constructor;
  15673. return new Ctor(clone(this.option));
  15674. },
  15675. setReadOnly: function (properties) {
  15676. // clazzUtil.setReadOnly(this, properties);
  15677. },
  15678. // If path is null/undefined, return null/undefined.
  15679. parsePath: function (path) {
  15680. if (typeof path === 'string') {
  15681. path = path.split('.');
  15682. }
  15683. return path;
  15684. },
  15685. /**
  15686. * @param {Function} getParentMethod
  15687. * param {Array.<string>|string} path
  15688. * return {module:echarts/model/Model}
  15689. */
  15690. customizeGetParent: function (getParentMethod) {
  15691. inner(this).getParent = getParentMethod;
  15692. },
  15693. isAnimationEnabled: function () {
  15694. if (!env$1.node) {
  15695. if (this.option.animation != null) {
  15696. return !!this.option.animation;
  15697. }
  15698. else if (this.parentModel) {
  15699. return this.parentModel.isAnimationEnabled();
  15700. }
  15701. }
  15702. }
  15703. };
  15704. function doGet(obj, pathArr, parentModel) {
  15705. for (var i = 0; i < pathArr.length; i++) {
  15706. // Ignore empty
  15707. if (!pathArr[i]) {
  15708. continue;
  15709. }
  15710. // obj could be number/string/... (like 0)
  15711. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  15712. if (obj == null) {
  15713. break;
  15714. }
  15715. }
  15716. if (obj == null && parentModel) {
  15717. obj = parentModel.get(pathArr);
  15718. }
  15719. return obj;
  15720. }
  15721. // `path` can be null/undefined
  15722. function getParent(model, path) {
  15723. var getParentMethod = inner(model).getParent;
  15724. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  15725. }
  15726. // Enable Model.extend.
  15727. enableClassExtend(Model);
  15728. enableClassCheck(Model);
  15729. mixin$1(Model, lineStyleMixin);
  15730. mixin$1(Model, areaStyleMixin);
  15731. mixin$1(Model, textStyleMixin);
  15732. mixin$1(Model, itemStyleMixin);
  15733. /*
  15734. * Licensed to the Apache Software Foundation (ASF) under one
  15735. * or more contributor license agreements. See the NOTICE file
  15736. * distributed with this work for additional information
  15737. * regarding copyright ownership. The ASF licenses this file
  15738. * to you under the Apache License, Version 2.0 (the
  15739. * "License"); you may not use this file except in compliance
  15740. * with the License. You may obtain a copy of the License at
  15741. *
  15742. * http://www.apache.org/licenses/LICENSE-2.0
  15743. *
  15744. * Unless required by applicable law or agreed to in writing,
  15745. * software distributed under the License is distributed on an
  15746. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15747. * KIND, either express or implied. See the License for the
  15748. * specific language governing permissions and limitations
  15749. * under the License.
  15750. */
  15751. var base = 0;
  15752. /**
  15753. * @public
  15754. * @param {string} type
  15755. * @return {string}
  15756. */
  15757. function getUID(type) {
  15758. // Considering the case of crossing js context,
  15759. // use Math.random to make id as unique as possible.
  15760. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  15761. }
  15762. /**
  15763. * @inner
  15764. */
  15765. function enableSubTypeDefaulter(entity) {
  15766. var subTypeDefaulters = {};
  15767. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  15768. componentType = parseClassType$1(componentType);
  15769. subTypeDefaulters[componentType.main] = defaulter;
  15770. };
  15771. entity.determineSubType = function (componentType, option) {
  15772. var type = option.type;
  15773. if (!type) {
  15774. var componentTypeMain = parseClassType$1(componentType).main;
  15775. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15776. type = subTypeDefaulters[componentTypeMain](option);
  15777. }
  15778. }
  15779. return type;
  15780. };
  15781. return entity;
  15782. }
  15783. /**
  15784. * Topological travel on Activity Network (Activity On Vertices).
  15785. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15786. *
  15787. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15788. *
  15789. * If there is circle dependencey, Error will be thrown.
  15790. *
  15791. */
  15792. function enableTopologicalTravel(entity, dependencyGetter) {
  15793. /**
  15794. * @public
  15795. * @param {Array.<string>} targetNameList Target Component type list.
  15796. * Can be ['aa', 'bb', 'aa.xx']
  15797. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  15798. * @param {Function} callback Params: componentType, dependencies.
  15799. * @param {Object} context Scope of callback.
  15800. */
  15801. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15802. if (!targetNameList.length) {
  15803. return;
  15804. }
  15805. var result = makeDepndencyGraph(fullNameList);
  15806. var graph = result.graph;
  15807. var stack = result.noEntryList;
  15808. var targetNameSet = {};
  15809. each$1(targetNameList, function (name) {
  15810. targetNameSet[name] = true;
  15811. });
  15812. while (stack.length) {
  15813. var currComponentType = stack.pop();
  15814. var currVertex = graph[currComponentType];
  15815. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15816. if (isInTargetNameSet) {
  15817. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15818. delete targetNameSet[currComponentType];
  15819. }
  15820. each$1(
  15821. currVertex.successor,
  15822. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  15823. );
  15824. }
  15825. each$1(targetNameSet, function () {
  15826. throw new Error('Circle dependency may exists');
  15827. });
  15828. function removeEdge(succComponentType) {
  15829. graph[succComponentType].entryCount--;
  15830. if (graph[succComponentType].entryCount === 0) {
  15831. stack.push(succComponentType);
  15832. }
  15833. }
  15834. // Consider this case: legend depends on series, and we call
  15835. // chart.setOption({series: [...]}), where only series is in option.
  15836. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15837. // not be called, but only sereis.mergeOption is called. Thus legend
  15838. // have no chance to update its local record about series (like which
  15839. // name of series is available in legend).
  15840. function removeEdgeAndAdd(succComponentType) {
  15841. targetNameSet[succComponentType] = true;
  15842. removeEdge(succComponentType);
  15843. }
  15844. };
  15845. /**
  15846. * DepndencyGraph: {Object}
  15847. * key: conponentType,
  15848. * value: {
  15849. * successor: [conponentTypes...],
  15850. * originalDeps: [conponentTypes...],
  15851. * entryCount: {number}
  15852. * }
  15853. */
  15854. function makeDepndencyGraph(fullNameList) {
  15855. var graph = {};
  15856. var noEntryList = [];
  15857. each$1(fullNameList, function (name) {
  15858. var thisItem = createDependencyGraphItem(graph, name);
  15859. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15860. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15861. thisItem.entryCount = availableDeps.length;
  15862. if (thisItem.entryCount === 0) {
  15863. noEntryList.push(name);
  15864. }
  15865. each$1(availableDeps, function (dependentName) {
  15866. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15867. thisItem.predecessor.push(dependentName);
  15868. }
  15869. var thatItem = createDependencyGraphItem(graph, dependentName);
  15870. if (indexOf(thatItem.successor, dependentName) < 0) {
  15871. thatItem.successor.push(name);
  15872. }
  15873. });
  15874. });
  15875. return {graph: graph, noEntryList: noEntryList};
  15876. }
  15877. function createDependencyGraphItem(graph, name) {
  15878. if (!graph[name]) {
  15879. graph[name] = {predecessor: [], successor: []};
  15880. }
  15881. return graph[name];
  15882. }
  15883. function getAvailableDependencies(originalDeps, fullNameList) {
  15884. var availableDeps = [];
  15885. each$1(originalDeps, function (dep) {
  15886. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15887. });
  15888. return availableDeps;
  15889. }
  15890. }
  15891. /*
  15892. * Licensed to the Apache Software Foundation (ASF) under one
  15893. * or more contributor license agreements. See the NOTICE file
  15894. * distributed with this work for additional information
  15895. * regarding copyright ownership. The ASF licenses this file
  15896. * to you under the Apache License, Version 2.0 (the
  15897. * "License"); you may not use this file except in compliance
  15898. * with the License. You may obtain a copy of the License at
  15899. *
  15900. * http://www.apache.org/licenses/LICENSE-2.0
  15901. *
  15902. * Unless required by applicable law or agreed to in writing,
  15903. * software distributed under the License is distributed on an
  15904. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15905. * KIND, either express or implied. See the License for the
  15906. * specific language governing permissions and limitations
  15907. * under the License.
  15908. */
  15909. /*
  15910. * A third-party license is embeded for some of the code in this file:
  15911. * The method "quantile" was copied from "d3.js".
  15912. * (See more details in the comment of the method below.)
  15913. * The use of the source code of this file is also subject to the terms
  15914. * and consitions of the license of "d3.js" (BSD-3Clause, see
  15915. * </licenses/LICENSE-d3>).
  15916. */
  15917. var RADIAN_EPSILON = 1e-4;
  15918. function _trim(str) {
  15919. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  15920. }
  15921. /**
  15922. * Linear mapping a value from domain to range
  15923. * @memberOf module:echarts/util/number
  15924. * @param {(number|Array.<number>)} val
  15925. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15926. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15927. * @param {boolean} clamp
  15928. * @return {(number|Array.<number>}
  15929. */
  15930. function linearMap(val, domain, range, clamp) {
  15931. var subDomain = domain[1] - domain[0];
  15932. var subRange = range[1] - range[0];
  15933. if (subDomain === 0) {
  15934. return subRange === 0
  15935. ? range[0]
  15936. : (range[0] + range[1]) / 2;
  15937. }
  15938. // Avoid accuracy problem in edge, such as
  15939. // 146.39 - 62.83 === 83.55999999999999.
  15940. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15941. // It is a little verbose for efficiency considering this method
  15942. // is a hotspot.
  15943. if (clamp) {
  15944. if (subDomain > 0) {
  15945. if (val <= domain[0]) {
  15946. return range[0];
  15947. }
  15948. else if (val >= domain[1]) {
  15949. return range[1];
  15950. }
  15951. }
  15952. else {
  15953. if (val >= domain[0]) {
  15954. return range[0];
  15955. }
  15956. else if (val <= domain[1]) {
  15957. return range[1];
  15958. }
  15959. }
  15960. }
  15961. else {
  15962. if (val === domain[0]) {
  15963. return range[0];
  15964. }
  15965. if (val === domain[1]) {
  15966. return range[1];
  15967. }
  15968. }
  15969. return (val - domain[0]) / subDomain * subRange + range[0];
  15970. }
  15971. /**
  15972. * Convert a percent string to absolute number.
  15973. * Returns NaN if percent is not a valid string or number
  15974. * @memberOf module:echarts/util/number
  15975. * @param {string|number} percent
  15976. * @param {number} all
  15977. * @return {number}
  15978. */
  15979. function parsePercent$1(percent, all) {
  15980. switch (percent) {
  15981. case 'center':
  15982. case 'middle':
  15983. percent = '50%';
  15984. break;
  15985. case 'left':
  15986. case 'top':
  15987. percent = '0%';
  15988. break;
  15989. case 'right':
  15990. case 'bottom':
  15991. percent = '100%';
  15992. break;
  15993. }
  15994. if (typeof percent === 'string') {
  15995. if (_trim(percent).match(/%$/)) {
  15996. return parseFloat(percent) / 100 * all;
  15997. }
  15998. return parseFloat(percent);
  15999. }
  16000. return percent == null ? NaN : +percent;
  16001. }
  16002. /**
  16003. * (1) Fix rounding error of float numbers.
  16004. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  16005. *
  16006. * @param {number} x
  16007. * @param {number} [precision]
  16008. * @param {boolean} [returnStr]
  16009. * @return {number|string}
  16010. */
  16011. function round$2(x, precision, returnStr) {
  16012. if (precision == null) {
  16013. precision = 10;
  16014. }
  16015. // Avoid range error
  16016. precision = Math.min(Math.max(0, precision), 20);
  16017. x = (+x).toFixed(precision);
  16018. return returnStr ? x : +x;
  16019. }
  16020. function asc(arr) {
  16021. arr.sort(function (a, b) {
  16022. return a - b;
  16023. });
  16024. return arr;
  16025. }
  16026. /**
  16027. * Get precision
  16028. * @param {number} val
  16029. */
  16030. function getPrecision(val) {
  16031. val = +val;
  16032. if (isNaN(val)) {
  16033. return 0;
  16034. }
  16035. // It is much faster than methods converting number to string as follows
  16036. // var tmp = val.toString();
  16037. // return tmp.length - 1 - tmp.indexOf('.');
  16038. // especially when precision is low
  16039. var e = 1;
  16040. var count = 0;
  16041. while (Math.round(val * e) / e !== val) {
  16042. e *= 10;
  16043. count++;
  16044. }
  16045. return count;
  16046. }
  16047. /**
  16048. * @param {string|number} val
  16049. * @return {number}
  16050. */
  16051. function getPrecisionSafe(val) {
  16052. var str = val.toString();
  16053. // Consider scientific notation: '3.4e-12' '3.4e+12'
  16054. var eIndex = str.indexOf('e');
  16055. if (eIndex > 0) {
  16056. var precision = +str.slice(eIndex + 1);
  16057. return precision < 0 ? -precision : 0;
  16058. }
  16059. else {
  16060. var dotIndex = str.indexOf('.');
  16061. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  16062. }
  16063. }
  16064. /**
  16065. * Minimal dicernible data precisioin according to a single pixel.
  16066. *
  16067. * @param {Array.<number>} dataExtent
  16068. * @param {Array.<number>} pixelExtent
  16069. * @return {number} precision
  16070. */
  16071. function getPixelPrecision(dataExtent, pixelExtent) {
  16072. var log = Math.log;
  16073. var LN10 = Math.LN10;
  16074. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  16075. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  16076. // toFixed() digits argument must be between 0 and 20.
  16077. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  16078. return !isFinite(precision) ? 20 : precision;
  16079. }
  16080. /**
  16081. * Get a data of given precision, assuring the sum of percentages
  16082. * in valueList is 1.
  16083. * The largest remainer method is used.
  16084. * https://en.wikipedia.org/wiki/Largest_remainder_method
  16085. *
  16086. * @param {Array.<number>} valueList a list of all data
  16087. * @param {number} idx index of the data to be processed in valueList
  16088. * @param {number} precision integer number showing digits of precision
  16089. * @return {number} percent ranging from 0 to 100
  16090. */
  16091. function getPercentWithPrecision(valueList, idx, precision) {
  16092. if (!valueList[idx]) {
  16093. return 0;
  16094. }
  16095. var sum = reduce(valueList, function (acc, val) {
  16096. return acc + (isNaN(val) ? 0 : val);
  16097. }, 0);
  16098. if (sum === 0) {
  16099. return 0;
  16100. }
  16101. var digits = Math.pow(10, precision);
  16102. var votesPerQuota = map(valueList, function (val) {
  16103. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  16104. });
  16105. var targetSeats = digits * 100;
  16106. var seats = map(votesPerQuota, function (votes) {
  16107. // Assign automatic seats.
  16108. return Math.floor(votes);
  16109. });
  16110. var currentSum = reduce(seats, function (acc, val) {
  16111. return acc + val;
  16112. }, 0);
  16113. var remainder = map(votesPerQuota, function (votes, idx) {
  16114. return votes - seats[idx];
  16115. });
  16116. // Has remainding votes.
  16117. while (currentSum < targetSeats) {
  16118. // Find next largest remainder.
  16119. var max = Number.NEGATIVE_INFINITY;
  16120. var maxId = null;
  16121. for (var i = 0, len = remainder.length; i < len; ++i) {
  16122. if (remainder[i] > max) {
  16123. max = remainder[i];
  16124. maxId = i;
  16125. }
  16126. }
  16127. // Add a vote to max remainder.
  16128. ++seats[maxId];
  16129. remainder[maxId] = 0;
  16130. ++currentSum;
  16131. }
  16132. return seats[idx] / digits;
  16133. }
  16134. // Number.MAX_SAFE_INTEGER, ie do not support.
  16135. var MAX_SAFE_INTEGER = 9007199254740991;
  16136. /**
  16137. * To 0 - 2 * PI, considering negative radian.
  16138. * @param {number} radian
  16139. * @return {number}
  16140. */
  16141. function remRadian(radian) {
  16142. var pi2 = Math.PI * 2;
  16143. return (radian % pi2 + pi2) % pi2;
  16144. }
  16145. /**
  16146. * @param {type} radian
  16147. * @return {boolean}
  16148. */
  16149. function isRadianAroundZero(val) {
  16150. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  16151. }
  16152. /* eslint-disable */
  16153. 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
  16154. /* eslint-enable */
  16155. /**
  16156. * @param {string|Date|number} value These values can be accepted:
  16157. * + An instance of Date, represent a time in its own time zone.
  16158. * + Or string in a subset of ISO 8601, only including:
  16159. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  16160. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  16161. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  16162. * all of which will be treated as local time if time zone is not specified
  16163. * (see <https://momentjs.com/>).
  16164. * + Or other string format, including (all of which will be treated as loacal time):
  16165. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  16166. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  16167. * + a timestamp, which represent a time in UTC.
  16168. * @return {Date} date
  16169. */
  16170. function parseDate(value) {
  16171. if (value instanceof Date) {
  16172. return value;
  16173. }
  16174. else if (typeof value === 'string') {
  16175. // Different browsers parse date in different way, so we parse it manually.
  16176. // Some other issues:
  16177. // new Date('1970-01-01') is UTC,
  16178. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  16179. // See issue #3623
  16180. var match = TIME_REG.exec(value);
  16181. if (!match) {
  16182. // return Invalid Date.
  16183. return new Date(NaN);
  16184. }
  16185. // Use local time when no timezone offset specifed.
  16186. if (!match[8]) {
  16187. // match[n] can only be string or undefined.
  16188. // But take care of '12' + 1 => '121'.
  16189. return new Date(
  16190. +match[1],
  16191. +(match[2] || 1) - 1,
  16192. +match[3] || 1,
  16193. +match[4] || 0,
  16194. +(match[5] || 0),
  16195. +match[6] || 0,
  16196. +match[7] || 0
  16197. );
  16198. }
  16199. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  16200. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  16201. // For example, system timezone is set as "Time Zone: America/Toronto",
  16202. // then these code will get different result:
  16203. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  16204. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  16205. // So we should not use `new Date`, but use `Date.UTC`.
  16206. else {
  16207. var hour = +match[4] || 0;
  16208. if (match[8].toUpperCase() !== 'Z') {
  16209. hour -= match[8].slice(0, 3);
  16210. }
  16211. return new Date(Date.UTC(
  16212. +match[1],
  16213. +(match[2] || 1) - 1,
  16214. +match[3] || 1,
  16215. hour,
  16216. +(match[5] || 0),
  16217. +match[6] || 0,
  16218. +match[7] || 0
  16219. ));
  16220. }
  16221. }
  16222. else if (value == null) {
  16223. return new Date(NaN);
  16224. }
  16225. return new Date(Math.round(value));
  16226. }
  16227. /**
  16228. * Quantity of a number. e.g. 0.1, 1, 10, 100
  16229. *
  16230. * @param {number} val
  16231. * @return {number}
  16232. */
  16233. function quantity(val) {
  16234. return Math.pow(10, quantityExponent(val));
  16235. }
  16236. function quantityExponent(val) {
  16237. return Math.floor(Math.log(val) / Math.LN10);
  16238. }
  16239. /**
  16240. * find a “nice” number approximately equal to x. Round the number if round = true,
  16241. * take ceiling if round = false. The primary observation is that the “nicest”
  16242. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  16243. *
  16244. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  16245. *
  16246. * @param {number} val Non-negative value.
  16247. * @param {boolean} round
  16248. * @return {number}
  16249. */
  16250. function nice(val, round) {
  16251. var exponent = quantityExponent(val);
  16252. var exp10 = Math.pow(10, exponent);
  16253. var f = val / exp10; // 1 <= f < 10
  16254. var nf;
  16255. if (round) {
  16256. if (f < 1.5) {
  16257. nf = 1;
  16258. }
  16259. else if (f < 2.5) {
  16260. nf = 2;
  16261. }
  16262. else if (f < 4) {
  16263. nf = 3;
  16264. }
  16265. else if (f < 7) {
  16266. nf = 5;
  16267. }
  16268. else {
  16269. nf = 10;
  16270. }
  16271. }
  16272. else {
  16273. if (f < 1) {
  16274. nf = 1;
  16275. }
  16276. else if (f < 2) {
  16277. nf = 2;
  16278. }
  16279. else if (f < 3) {
  16280. nf = 3;
  16281. }
  16282. else if (f < 5) {
  16283. nf = 5;
  16284. }
  16285. else {
  16286. nf = 10;
  16287. }
  16288. }
  16289. val = nf * exp10;
  16290. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  16291. // 20 is the uppper bound of toFixed.
  16292. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  16293. }
  16294. /**
  16295. * This code was copied from "d3.js"
  16296. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  16297. * See the license statement at the head of this file.
  16298. * @param {Array.<number>} ascArr
  16299. */
  16300. function quantile(ascArr, p) {
  16301. var H = (ascArr.length - 1) * p + 1;
  16302. var h = Math.floor(H);
  16303. var v = +ascArr[h - 1];
  16304. var e = H - h;
  16305. return e ? v + e * (ascArr[h] - v) : v;
  16306. }
  16307. /**
  16308. * Order intervals asc, and split them when overlap.
  16309. * expect(numberUtil.reformIntervals([
  16310. * {interval: [18, 62], close: [1, 1]},
  16311. * {interval: [-Infinity, -70], close: [0, 0]},
  16312. * {interval: [-70, -26], close: [1, 1]},
  16313. * {interval: [-26, 18], close: [1, 1]},
  16314. * {interval: [62, 150], close: [1, 1]},
  16315. * {interval: [106, 150], close: [1, 1]},
  16316. * {interval: [150, Infinity], close: [0, 0]}
  16317. * ])).toEqual([
  16318. * {interval: [-Infinity, -70], close: [0, 0]},
  16319. * {interval: [-70, -26], close: [1, 1]},
  16320. * {interval: [-26, 18], close: [0, 1]},
  16321. * {interval: [18, 62], close: [0, 1]},
  16322. * {interval: [62, 150], close: [0, 1]},
  16323. * {interval: [150, Infinity], close: [0, 0]}
  16324. * ]);
  16325. * @param {Array.<Object>} list, where `close` mean open or close
  16326. * of the interval, and Infinity can be used.
  16327. * @return {Array.<Object>} The origin list, which has been reformed.
  16328. */
  16329. function reformIntervals(list) {
  16330. list.sort(function (a, b) {
  16331. return littleThan(a, b, 0) ? -1 : 1;
  16332. });
  16333. var curr = -Infinity;
  16334. var currClose = 1;
  16335. for (var i = 0; i < list.length;) {
  16336. var interval = list[i].interval;
  16337. var close = list[i].close;
  16338. for (var lg = 0; lg < 2; lg++) {
  16339. if (interval[lg] <= curr) {
  16340. interval[lg] = curr;
  16341. close[lg] = !lg ? 1 - currClose : 1;
  16342. }
  16343. curr = interval[lg];
  16344. currClose = close[lg];
  16345. }
  16346. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  16347. list.splice(i, 1);
  16348. }
  16349. else {
  16350. i++;
  16351. }
  16352. }
  16353. return list;
  16354. function littleThan(a, b, lg) {
  16355. return a.interval[lg] < b.interval[lg]
  16356. || (
  16357. a.interval[lg] === b.interval[lg]
  16358. && (
  16359. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  16360. || (!lg && littleThan(a, b, 1))
  16361. )
  16362. );
  16363. }
  16364. }
  16365. /**
  16366. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  16367. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  16368. * subtraction forces infinities to NaN
  16369. *
  16370. * @param {*} v
  16371. * @return {boolean}
  16372. */
  16373. function isNumeric(v) {
  16374. return v - parseFloat(v) >= 0;
  16375. }
  16376. var number = (Object.freeze || Object)({
  16377. linearMap: linearMap,
  16378. parsePercent: parsePercent$1,
  16379. round: round$2,
  16380. asc: asc,
  16381. getPrecision: getPrecision,
  16382. getPrecisionSafe: getPrecisionSafe,
  16383. getPixelPrecision: getPixelPrecision,
  16384. getPercentWithPrecision: getPercentWithPrecision,
  16385. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  16386. remRadian: remRadian,
  16387. isRadianAroundZero: isRadianAroundZero,
  16388. parseDate: parseDate,
  16389. quantity: quantity,
  16390. nice: nice,
  16391. quantile: quantile,
  16392. reformIntervals: reformIntervals,
  16393. isNumeric: isNumeric
  16394. });
  16395. /*
  16396. * Licensed to the Apache Software Foundation (ASF) under one
  16397. * or more contributor license agreements. See the NOTICE file
  16398. * distributed with this work for additional information
  16399. * regarding copyright ownership. The ASF licenses this file
  16400. * to you under the Apache License, Version 2.0 (the
  16401. * "License"); you may not use this file except in compliance
  16402. * with the License. You may obtain a copy of the License at
  16403. *
  16404. * http://www.apache.org/licenses/LICENSE-2.0
  16405. *
  16406. * Unless required by applicable law or agreed to in writing,
  16407. * software distributed under the License is distributed on an
  16408. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16409. * KIND, either express or implied. See the License for the
  16410. * specific language governing permissions and limitations
  16411. * under the License.
  16412. */
  16413. // import Text from 'zrender/src/graphic/Text';
  16414. /**
  16415. * 每三位默认加,格式化
  16416. * @param {string|number} x
  16417. * @return {string}
  16418. */
  16419. function addCommas(x) {
  16420. if (isNaN(x)) {
  16421. return '-';
  16422. }
  16423. x = (x + '').split('.');
  16424. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  16425. + (x.length > 1 ? ('.' + x[1]) : '');
  16426. }
  16427. /**
  16428. * @param {string} str
  16429. * @param {boolean} [upperCaseFirst=false]
  16430. * @return {string} str
  16431. */
  16432. function toCamelCase(str, upperCaseFirst) {
  16433. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  16434. return group1.toUpperCase();
  16435. });
  16436. if (upperCaseFirst && str) {
  16437. str = str.charAt(0).toUpperCase() + str.slice(1);
  16438. }
  16439. return str;
  16440. }
  16441. var normalizeCssArray$1 = normalizeCssArray;
  16442. var replaceReg = /([&<>"'])/g;
  16443. var replaceMap = {
  16444. '&': '&amp;',
  16445. '<': '&lt;',
  16446. '>': '&gt;',
  16447. '"': '&quot;',
  16448. '\'': '&#39;'
  16449. };
  16450. function encodeHTML(source) {
  16451. return source == null
  16452. ? ''
  16453. : (source + '').replace(replaceReg, function (str, c) {
  16454. return replaceMap[c];
  16455. });
  16456. }
  16457. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16458. var wrapVar = function (varName, seriesIdx) {
  16459. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16460. };
  16461. /**
  16462. * Template formatter
  16463. * @param {string} tpl
  16464. * @param {Array.<Object>|Object} paramsList
  16465. * @param {boolean} [encode=false]
  16466. * @return {string}
  16467. */
  16468. function formatTpl(tpl, paramsList, encode) {
  16469. if (!isArray(paramsList)) {
  16470. paramsList = [paramsList];
  16471. }
  16472. var seriesLen = paramsList.length;
  16473. if (!seriesLen) {
  16474. return '';
  16475. }
  16476. var $vars = paramsList[0].$vars || [];
  16477. for (var i = 0; i < $vars.length; i++) {
  16478. var alias = TPL_VAR_ALIAS[i];
  16479. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16480. }
  16481. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16482. for (var k = 0; k < $vars.length; k++) {
  16483. var val = paramsList[seriesIdx][$vars[k]];
  16484. tpl = tpl.replace(
  16485. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  16486. encode ? encodeHTML(val) : val
  16487. );
  16488. }
  16489. }
  16490. return tpl;
  16491. }
  16492. /**
  16493. * simple Template formatter
  16494. *
  16495. * @param {string} tpl
  16496. * @param {Object} param
  16497. * @param {boolean} [encode=false]
  16498. * @return {string}
  16499. */
  16500. function formatTplSimple(tpl, param, encode) {
  16501. each$1(param, function (value, key) {
  16502. tpl = tpl.replace(
  16503. '{' + key + '}',
  16504. encode ? encodeHTML(value) : value
  16505. );
  16506. });
  16507. return tpl;
  16508. }
  16509. /**
  16510. * @param {Object|string} [opt] If string, means color.
  16511. * @param {string} [opt.color]
  16512. * @param {string} [opt.extraCssText]
  16513. * @param {string} [opt.type='item'] 'item' or 'subItem'
  16514. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  16515. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  16516. * @return {string}
  16517. */
  16518. function getTooltipMarker(opt, extraCssText) {
  16519. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  16520. var color = opt.color;
  16521. var type = opt.type;
  16522. var extraCssText = opt.extraCssText;
  16523. var renderMode = opt.renderMode || 'html';
  16524. var markerId = opt.markerId || 'X';
  16525. if (!color) {
  16526. return '';
  16527. }
  16528. if (renderMode === 'html') {
  16529. return type === 'subItem'
  16530. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  16531. + 'border-radius:4px;width:4px;height:4px;background-color:'
  16532. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  16533. : '<span style="display:inline-block;margin-right:5px;'
  16534. + 'border-radius:10px;width:10px;height:10px;background-color:'
  16535. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  16536. }
  16537. else {
  16538. // Space for rich element marker
  16539. return {
  16540. renderMode: renderMode,
  16541. content: '{marker' + markerId + '|} ',
  16542. style: {
  16543. color: color
  16544. }
  16545. };
  16546. }
  16547. }
  16548. function pad(str, len) {
  16549. str += '';
  16550. return '0000'.substr(0, len - str.length) + str;
  16551. }
  16552. /**
  16553. * ISO Date format
  16554. * @param {string} tpl
  16555. * @param {number} value
  16556. * @param {boolean} [isUTC=false] Default in local time.
  16557. * see `module:echarts/scale/Time`
  16558. * and `module:echarts/util/number#parseDate`.
  16559. * @inner
  16560. */
  16561. function formatTime(tpl, value, isUTC) {
  16562. if (tpl === 'week'
  16563. || tpl === 'month'
  16564. || tpl === 'quarter'
  16565. || tpl === 'half-year'
  16566. || tpl === 'year'
  16567. ) {
  16568. tpl = 'MM-dd\nyyyy';
  16569. }
  16570. var date = parseDate(value);
  16571. var utc = isUTC ? 'UTC' : '';
  16572. var y = date['get' + utc + 'FullYear']();
  16573. var M = date['get' + utc + 'Month']() + 1;
  16574. var d = date['get' + utc + 'Date']();
  16575. var h = date['get' + utc + 'Hours']();
  16576. var m = date['get' + utc + 'Minutes']();
  16577. var s = date['get' + utc + 'Seconds']();
  16578. var S = date['get' + utc + 'Milliseconds']();
  16579. tpl = tpl.replace('MM', pad(M, 2))
  16580. .replace('M', M)
  16581. .replace('yyyy', y)
  16582. .replace('yy', y % 100)
  16583. .replace('dd', pad(d, 2))
  16584. .replace('d', d)
  16585. .replace('hh', pad(h, 2))
  16586. .replace('h', h)
  16587. .replace('mm', pad(m, 2))
  16588. .replace('m', m)
  16589. .replace('ss', pad(s, 2))
  16590. .replace('s', s)
  16591. .replace('SSS', pad(S, 3));
  16592. return tpl;
  16593. }
  16594. /**
  16595. * Capital first
  16596. * @param {string} str
  16597. * @return {string}
  16598. */
  16599. function capitalFirst(str) {
  16600. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16601. }
  16602. var truncateText$1 = truncateText;
  16603. /**
  16604. * @public
  16605. * @param {Object} opt
  16606. * @param {string} opt.text
  16607. * @param {string} opt.font
  16608. * @param {string} [opt.textAlign='left']
  16609. * @param {string} [opt.textVerticalAlign='top']
  16610. * @param {Array.<number>} [opt.textPadding]
  16611. * @param {number} [opt.textLineHeight]
  16612. * @param {Object} [opt.rich]
  16613. * @param {Object} [opt.truncate]
  16614. * @return {Object} {x, y, width, height, lineHeight}
  16615. */
  16616. function getTextBoundingRect(opt) {
  16617. return getBoundingRect(
  16618. opt.text,
  16619. opt.font,
  16620. opt.textAlign,
  16621. opt.textVerticalAlign,
  16622. opt.textPadding,
  16623. opt.textLineHeight,
  16624. opt.rich,
  16625. opt.truncate
  16626. );
  16627. }
  16628. /**
  16629. * @deprecated
  16630. * the `textLineHeight` was added later.
  16631. * For backward compatiblility, put it as the last parameter.
  16632. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  16633. */
  16634. function getTextRect(
  16635. text, font, textAlign, textVerticalAlign, textPadding, rich, truncate, textLineHeight
  16636. ) {
  16637. return getBoundingRect(
  16638. text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate
  16639. );
  16640. }
  16641. var format = (Object.freeze || Object)({
  16642. addCommas: addCommas,
  16643. toCamelCase: toCamelCase,
  16644. normalizeCssArray: normalizeCssArray$1,
  16645. encodeHTML: encodeHTML,
  16646. formatTpl: formatTpl,
  16647. formatTplSimple: formatTplSimple,
  16648. getTooltipMarker: getTooltipMarker,
  16649. formatTime: formatTime,
  16650. capitalFirst: capitalFirst,
  16651. truncateText: truncateText$1,
  16652. getTextBoundingRect: getTextBoundingRect,
  16653. getTextRect: getTextRect
  16654. });
  16655. /*
  16656. * Licensed to the Apache Software Foundation (ASF) under one
  16657. * or more contributor license agreements. See the NOTICE file
  16658. * distributed with this work for additional information
  16659. * regarding copyright ownership. The ASF licenses this file
  16660. * to you under the Apache License, Version 2.0 (the
  16661. * "License"); you may not use this file except in compliance
  16662. * with the License. You may obtain a copy of the License at
  16663. *
  16664. * http://www.apache.org/licenses/LICENSE-2.0
  16665. *
  16666. * Unless required by applicable law or agreed to in writing,
  16667. * software distributed under the License is distributed on an
  16668. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16669. * KIND, either express or implied. See the License for the
  16670. * specific language governing permissions and limitations
  16671. * under the License.
  16672. */
  16673. // Layout helpers for each component positioning
  16674. var each$3 = each$1;
  16675. /**
  16676. * @public
  16677. */
  16678. var LOCATION_PARAMS = [
  16679. 'left', 'right', 'top', 'bottom', 'width', 'height'
  16680. ];
  16681. /**
  16682. * @public
  16683. */
  16684. var HV_NAMES = [
  16685. ['width', 'left', 'right'],
  16686. ['height', 'top', 'bottom']
  16687. ];
  16688. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16689. var x = 0;
  16690. var y = 0;
  16691. if (maxWidth == null) {
  16692. maxWidth = Infinity;
  16693. }
  16694. if (maxHeight == null) {
  16695. maxHeight = Infinity;
  16696. }
  16697. var currentLineMaxSize = 0;
  16698. group.eachChild(function (child, idx) {
  16699. var position = child.position;
  16700. var rect = child.getBoundingRect();
  16701. var nextChild = group.childAt(idx + 1);
  16702. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16703. var nextX;
  16704. var nextY;
  16705. if (orient === 'horizontal') {
  16706. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  16707. nextX = x + moveX;
  16708. // Wrap when width exceeds maxWidth or meet a `newline` group
  16709. // FIXME compare before adding gap?
  16710. if (nextX > maxWidth || child.newline) {
  16711. x = 0;
  16712. nextX = moveX;
  16713. y += currentLineMaxSize + gap;
  16714. currentLineMaxSize = rect.height;
  16715. }
  16716. else {
  16717. // FIXME: consider rect.y is not `0`?
  16718. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16719. }
  16720. }
  16721. else {
  16722. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  16723. nextY = y + moveY;
  16724. // Wrap when width exceeds maxHeight or meet a `newline` group
  16725. if (nextY > maxHeight || child.newline) {
  16726. x += currentLineMaxSize + gap;
  16727. y = 0;
  16728. nextY = moveY;
  16729. currentLineMaxSize = rect.width;
  16730. }
  16731. else {
  16732. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16733. }
  16734. }
  16735. if (child.newline) {
  16736. return;
  16737. }
  16738. position[0] = x;
  16739. position[1] = y;
  16740. orient === 'horizontal'
  16741. ? (x = nextX + gap)
  16742. : (y = nextY + gap);
  16743. });
  16744. }
  16745. /**
  16746. * VBox or HBox layouting
  16747. * @param {string} orient
  16748. * @param {module:zrender/container/Group} group
  16749. * @param {number} gap
  16750. * @param {number} [width=Infinity]
  16751. * @param {number} [height=Infinity]
  16752. */
  16753. var box = boxLayout;
  16754. /**
  16755. * VBox layouting
  16756. * @param {module:zrender/container/Group} group
  16757. * @param {number} gap
  16758. * @param {number} [width=Infinity]
  16759. * @param {number} [height=Infinity]
  16760. */
  16761. var vbox = curry(boxLayout, 'vertical');
  16762. /**
  16763. * HBox layouting
  16764. * @param {module:zrender/container/Group} group
  16765. * @param {number} gap
  16766. * @param {number} [width=Infinity]
  16767. * @param {number} [height=Infinity]
  16768. */
  16769. var hbox = curry(boxLayout, 'horizontal');
  16770. /**
  16771. * If x or x2 is not specified or 'center' 'left' 'right',
  16772. * the width would be as long as possible.
  16773. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16774. * the height would be as long as possible.
  16775. *
  16776. * @param {Object} positionInfo
  16777. * @param {number|string} [positionInfo.x]
  16778. * @param {number|string} [positionInfo.y]
  16779. * @param {number|string} [positionInfo.x2]
  16780. * @param {number|string} [positionInfo.y2]
  16781. * @param {Object} containerRect {width, height}
  16782. * @param {string|number} margin
  16783. * @return {Object} {width, height}
  16784. */
  16785. function getAvailableSize(positionInfo, containerRect, margin) {
  16786. var containerWidth = containerRect.width;
  16787. var containerHeight = containerRect.height;
  16788. var x = parsePercent$1(positionInfo.x, containerWidth);
  16789. var y = parsePercent$1(positionInfo.y, containerHeight);
  16790. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  16791. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  16792. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  16793. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  16794. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  16795. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  16796. margin = normalizeCssArray$1(margin || 0);
  16797. return {
  16798. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  16799. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  16800. };
  16801. }
  16802. /**
  16803. * Parse position info.
  16804. *
  16805. * @param {Object} positionInfo
  16806. * @param {number|string} [positionInfo.left]
  16807. * @param {number|string} [positionInfo.top]
  16808. * @param {number|string} [positionInfo.right]
  16809. * @param {number|string} [positionInfo.bottom]
  16810. * @param {number|string} [positionInfo.width]
  16811. * @param {number|string} [positionInfo.height]
  16812. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  16813. * @param {Object} containerRect
  16814. * @param {string|number} [margin]
  16815. *
  16816. * @return {module:zrender/core/BoundingRect}
  16817. */
  16818. function getLayoutRect(
  16819. positionInfo, containerRect, margin
  16820. ) {
  16821. margin = normalizeCssArray$1(margin || 0);
  16822. var containerWidth = containerRect.width;
  16823. var containerHeight = containerRect.height;
  16824. var left = parsePercent$1(positionInfo.left, containerWidth);
  16825. var top = parsePercent$1(positionInfo.top, containerHeight);
  16826. var right = parsePercent$1(positionInfo.right, containerWidth);
  16827. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16828. var width = parsePercent$1(positionInfo.width, containerWidth);
  16829. var height = parsePercent$1(positionInfo.height, containerHeight);
  16830. var verticalMargin = margin[2] + margin[0];
  16831. var horizontalMargin = margin[1] + margin[3];
  16832. var aspect = positionInfo.aspect;
  16833. // If width is not specified, calculate width from left and right
  16834. if (isNaN(width)) {
  16835. width = containerWidth - right - horizontalMargin - left;
  16836. }
  16837. if (isNaN(height)) {
  16838. height = containerHeight - bottom - verticalMargin - top;
  16839. }
  16840. if (aspect != null) {
  16841. // If width and height are not given
  16842. // 1. Graph should not exceeds the container
  16843. // 2. Aspect must be keeped
  16844. // 3. Graph should take the space as more as possible
  16845. // FIXME
  16846. // Margin is not considered, because there is no case that both
  16847. // using margin and aspect so far.
  16848. if (isNaN(width) && isNaN(height)) {
  16849. if (aspect > containerWidth / containerHeight) {
  16850. width = containerWidth * 0.8;
  16851. }
  16852. else {
  16853. height = containerHeight * 0.8;
  16854. }
  16855. }
  16856. // Calculate width or height with given aspect
  16857. if (isNaN(width)) {
  16858. width = aspect * height;
  16859. }
  16860. if (isNaN(height)) {
  16861. height = width / aspect;
  16862. }
  16863. }
  16864. // If left is not specified, calculate left from right and width
  16865. if (isNaN(left)) {
  16866. left = containerWidth - right - width - horizontalMargin;
  16867. }
  16868. if (isNaN(top)) {
  16869. top = containerHeight - bottom - height - verticalMargin;
  16870. }
  16871. // Align left and top
  16872. switch (positionInfo.left || positionInfo.right) {
  16873. case 'center':
  16874. left = containerWidth / 2 - width / 2 - margin[3];
  16875. break;
  16876. case 'right':
  16877. left = containerWidth - width - horizontalMargin;
  16878. break;
  16879. }
  16880. switch (positionInfo.top || positionInfo.bottom) {
  16881. case 'middle':
  16882. case 'center':
  16883. top = containerHeight / 2 - height / 2 - margin[0];
  16884. break;
  16885. case 'bottom':
  16886. top = containerHeight - height - verticalMargin;
  16887. break;
  16888. }
  16889. // If something is wrong and left, top, width, height are calculated as NaN
  16890. left = left || 0;
  16891. top = top || 0;
  16892. if (isNaN(width)) {
  16893. // Width may be NaN if only one value is given except width
  16894. width = containerWidth - horizontalMargin - left - (right || 0);
  16895. }
  16896. if (isNaN(height)) {
  16897. // Height may be NaN if only one value is given except height
  16898. height = containerHeight - verticalMargin - top - (bottom || 0);
  16899. }
  16900. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16901. rect.margin = margin;
  16902. return rect;
  16903. }
  16904. /**
  16905. * Position a zr element in viewport
  16906. * Group position is specified by either
  16907. * {left, top}, {right, bottom}
  16908. * If all properties exists, right and bottom will be igonred.
  16909. *
  16910. * Logic:
  16911. * 1. Scale (against origin point in parent coord)
  16912. * 2. Rotate (against origin point in parent coord)
  16913. * 3. Traslate (with el.position by this method)
  16914. * So this method only fixes the last step 'Traslate', which does not affect
  16915. * scaling and rotating.
  16916. *
  16917. * If be called repeatly with the same input el, the same result will be gotten.
  16918. *
  16919. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  16920. * @param {Object} positionInfo
  16921. * @param {number|string} [positionInfo.left]
  16922. * @param {number|string} [positionInfo.top]
  16923. * @param {number|string} [positionInfo.right]
  16924. * @param {number|string} [positionInfo.bottom]
  16925. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  16926. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  16927. * @param {Object} containerRect
  16928. * @param {string|number} margin
  16929. * @param {Object} [opt]
  16930. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  16931. * @param {Array.<number>} [opt.boundingMode='all']
  16932. * Specify how to calculate boundingRect when locating.
  16933. * 'all': Position the boundingRect that is transformed and uioned
  16934. * both itself and its descendants.
  16935. * This mode simplies confine the elements in the bounding
  16936. * of their container (e.g., using 'right: 0').
  16937. * 'raw': Position the boundingRect that is not transformed and only itself.
  16938. * This mode is useful when you want a element can overflow its
  16939. * container. (Consider a rotated circle needs to be located in a corner.)
  16940. * In this mode positionInfo.width/height can only be number.
  16941. */
  16942. function positionElement(el, positionInfo, containerRect, margin, opt) {
  16943. var h = !opt || !opt.hv || opt.hv[0];
  16944. var v = !opt || !opt.hv || opt.hv[1];
  16945. var boundingMode = opt && opt.boundingMode || 'all';
  16946. if (!h && !v) {
  16947. return;
  16948. }
  16949. var rect;
  16950. if (boundingMode === 'raw') {
  16951. rect = el.type === 'group'
  16952. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  16953. : el.getBoundingRect();
  16954. }
  16955. else {
  16956. rect = el.getBoundingRect();
  16957. if (el.needLocalTransform()) {
  16958. var transform = el.getLocalTransform();
  16959. // Notice: raw rect may be inner object of el,
  16960. // which should not be modified.
  16961. rect = rect.clone();
  16962. rect.applyTransform(transform);
  16963. }
  16964. }
  16965. // The real width and height can not be specified but calculated by the given el.
  16966. positionInfo = getLayoutRect(
  16967. defaults(
  16968. {width: rect.width, height: rect.height},
  16969. positionInfo
  16970. ),
  16971. containerRect,
  16972. margin
  16973. );
  16974. // Because 'tranlate' is the last step in transform
  16975. // (see zrender/core/Transformable#getLocalTransform),
  16976. // we can just only modify el.position to get final result.
  16977. var elPos = el.position;
  16978. var dx = h ? positionInfo.x - rect.x : 0;
  16979. var dy = v ? positionInfo.y - rect.y : 0;
  16980. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  16981. }
  16982. /**
  16983. * @param {Object} option Contains some of the properties in HV_NAMES.
  16984. * @param {number} hvIdx 0: horizontal; 1: vertical.
  16985. */
  16986. function sizeCalculable(option, hvIdx) {
  16987. return option[HV_NAMES[hvIdx][0]] != null
  16988. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  16989. }
  16990. /**
  16991. * Consider Case:
  16992. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  16993. * through setOption or media query, using normal zrUtil.merge will cause
  16994. * {right: 0} does not take effect.
  16995. *
  16996. * @example
  16997. * ComponentModel.extend({
  16998. * init: function () {
  16999. * ...
  17000. * var inputPositionParams = layout.getLayoutParams(option);
  17001. * this.mergeOption(inputPositionParams);
  17002. * },
  17003. * mergeOption: function (newOption) {
  17004. * newOption && zrUtil.merge(thisOption, newOption, true);
  17005. * layout.mergeLayoutParam(thisOption, newOption);
  17006. * }
  17007. * });
  17008. *
  17009. * @param {Object} targetOption
  17010. * @param {Object} newOption
  17011. * @param {Object|string} [opt]
  17012. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  17013. * that width (or height) should not be calculated by left and right (or top and bottom).
  17014. */
  17015. function mergeLayoutParam(targetOption, newOption, opt) {
  17016. !isObject$1(opt) && (opt = {});
  17017. var ignoreSize = opt.ignoreSize;
  17018. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  17019. var hResult = merge$$1(HV_NAMES[0], 0);
  17020. var vResult = merge$$1(HV_NAMES[1], 1);
  17021. copy(HV_NAMES[0], targetOption, hResult);
  17022. copy(HV_NAMES[1], targetOption, vResult);
  17023. function merge$$1(names, hvIdx) {
  17024. var newParams = {};
  17025. var newValueCount = 0;
  17026. var merged = {};
  17027. var mergedValueCount = 0;
  17028. var enoughParamNumber = 2;
  17029. each$3(names, function (name) {
  17030. merged[name] = targetOption[name];
  17031. });
  17032. each$3(names, function (name) {
  17033. // Consider case: newOption.width is null, which is
  17034. // set by user for removing width setting.
  17035. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  17036. hasValue(newParams, name) && newValueCount++;
  17037. hasValue(merged, name) && mergedValueCount++;
  17038. });
  17039. if (ignoreSize[hvIdx]) {
  17040. // Only one of left/right is premitted to exist.
  17041. if (hasValue(newOption, names[1])) {
  17042. merged[names[2]] = null;
  17043. }
  17044. else if (hasValue(newOption, names[2])) {
  17045. merged[names[1]] = null;
  17046. }
  17047. return merged;
  17048. }
  17049. // Case: newOption: {width: ..., right: ...},
  17050. // or targetOption: {right: ...} and newOption: {width: ...},
  17051. // There is no conflict when merged only has params count
  17052. // little than enoughParamNumber.
  17053. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  17054. return merged;
  17055. }
  17056. // Case: newOption: {width: ..., right: ...},
  17057. // Than we can make sure user only want those two, and ignore
  17058. // all origin params in targetOption.
  17059. else if (newValueCount >= enoughParamNumber) {
  17060. return newParams;
  17061. }
  17062. else {
  17063. // Chose another param from targetOption by priority.
  17064. for (var i = 0; i < names.length; i++) {
  17065. var name = names[i];
  17066. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  17067. newParams[name] = targetOption[name];
  17068. break;
  17069. }
  17070. }
  17071. return newParams;
  17072. }
  17073. }
  17074. function hasProp(obj, name) {
  17075. return obj.hasOwnProperty(name);
  17076. }
  17077. function hasValue(obj, name) {
  17078. return obj[name] != null && obj[name] !== 'auto';
  17079. }
  17080. function copy(names, target, source) {
  17081. each$3(names, function (name) {
  17082. target[name] = source[name];
  17083. });
  17084. }
  17085. }
  17086. /**
  17087. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17088. * @param {Object} source
  17089. * @return {Object} Result contains those props.
  17090. */
  17091. function getLayoutParams(source) {
  17092. return copyLayoutParams({}, source);
  17093. }
  17094. /**
  17095. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17096. * @param {Object} source
  17097. * @return {Object} Result contains those props.
  17098. */
  17099. function copyLayoutParams(target, source) {
  17100. source && target && each$3(LOCATION_PARAMS, function (name) {
  17101. source.hasOwnProperty(name) && (target[name] = source[name]);
  17102. });
  17103. return target;
  17104. }
  17105. /*
  17106. * Licensed to the Apache Software Foundation (ASF) under one
  17107. * or more contributor license agreements. See the NOTICE file
  17108. * distributed with this work for additional information
  17109. * regarding copyright ownership. The ASF licenses this file
  17110. * to you under the Apache License, Version 2.0 (the
  17111. * "License"); you may not use this file except in compliance
  17112. * with the License. You may obtain a copy of the License at
  17113. *
  17114. * http://www.apache.org/licenses/LICENSE-2.0
  17115. *
  17116. * Unless required by applicable law or agreed to in writing,
  17117. * software distributed under the License is distributed on an
  17118. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17119. * KIND, either express or implied. See the License for the
  17120. * specific language governing permissions and limitations
  17121. * under the License.
  17122. */
  17123. var boxLayoutMixin = {
  17124. getBoxLayoutParams: function () {
  17125. return {
  17126. left: this.get('left'),
  17127. top: this.get('top'),
  17128. right: this.get('right'),
  17129. bottom: this.get('bottom'),
  17130. width: this.get('width'),
  17131. height: this.get('height')
  17132. };
  17133. }
  17134. };
  17135. /*
  17136. * Licensed to the Apache Software Foundation (ASF) under one
  17137. * or more contributor license agreements. See the NOTICE file
  17138. * distributed with this work for additional information
  17139. * regarding copyright ownership. The ASF licenses this file
  17140. * to you under the Apache License, Version 2.0 (the
  17141. * "License"); you may not use this file except in compliance
  17142. * with the License. You may obtain a copy of the License at
  17143. *
  17144. * http://www.apache.org/licenses/LICENSE-2.0
  17145. *
  17146. * Unless required by applicable law or agreed to in writing,
  17147. * software distributed under the License is distributed on an
  17148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17149. * KIND, either express or implied. See the License for the
  17150. * specific language governing permissions and limitations
  17151. * under the License.
  17152. */
  17153. /**
  17154. * Component model
  17155. *
  17156. * @module echarts/model/Component
  17157. */
  17158. var inner$1 = makeInner();
  17159. /**
  17160. * @alias module:echarts/model/Component
  17161. * @constructor
  17162. * @param {Object} option
  17163. * @param {module:echarts/model/Model} parentModel
  17164. * @param {module:echarts/model/Model} ecModel
  17165. */
  17166. var ComponentModel = Model.extend({
  17167. type: 'component',
  17168. /**
  17169. * @readOnly
  17170. * @type {string}
  17171. */
  17172. id: '',
  17173. /**
  17174. * Because simplified concept is probably better, series.name (or component.name)
  17175. * has been having too many resposibilities:
  17176. * (1) Generating id (which requires name in option should not be modified).
  17177. * (2) As an index to mapping series when merging option or calling API (a name
  17178. * can refer to more then one components, which is convinient is some case).
  17179. * (3) Display.
  17180. * @readOnly
  17181. */
  17182. name: '',
  17183. /**
  17184. * @readOnly
  17185. * @type {string}
  17186. */
  17187. mainType: '',
  17188. /**
  17189. * @readOnly
  17190. * @type {string}
  17191. */
  17192. subType: '',
  17193. /**
  17194. * @readOnly
  17195. * @type {number}
  17196. */
  17197. componentIndex: 0,
  17198. /**
  17199. * @type {Object}
  17200. * @protected
  17201. */
  17202. defaultOption: null,
  17203. /**
  17204. * @type {module:echarts/model/Global}
  17205. * @readOnly
  17206. */
  17207. ecModel: null,
  17208. /**
  17209. * key: componentType
  17210. * value: Component model list, can not be null.
  17211. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17212. * @readOnly
  17213. */
  17214. dependentModels: [],
  17215. /**
  17216. * @type {string}
  17217. * @readOnly
  17218. */
  17219. uid: null,
  17220. /**
  17221. * Support merge layout params.
  17222. * Only support 'box' now (left/right/top/bottom/width/height).
  17223. * @type {string|Object} Object can be {ignoreSize: true}
  17224. * @readOnly
  17225. */
  17226. layoutMode: null,
  17227. $constructor: function (option, parentModel, ecModel, extraOpt) {
  17228. Model.call(this, option, parentModel, ecModel, extraOpt);
  17229. this.uid = getUID('ec_cpt_model');
  17230. },
  17231. init: function (option, parentModel, ecModel, extraOpt) {
  17232. this.mergeDefaultAndTheme(option, ecModel);
  17233. },
  17234. mergeDefaultAndTheme: function (option, ecModel) {
  17235. var layoutMode = this.layoutMode;
  17236. var inputPositionParams = layoutMode
  17237. ? getLayoutParams(option) : {};
  17238. var themeModel = ecModel.getTheme();
  17239. merge(option, themeModel.get(this.mainType));
  17240. merge(option, this.getDefaultOption());
  17241. if (layoutMode) {
  17242. mergeLayoutParam(option, inputPositionParams, layoutMode);
  17243. }
  17244. },
  17245. mergeOption: function (option, extraOpt) {
  17246. merge(this.option, option, true);
  17247. var layoutMode = this.layoutMode;
  17248. if (layoutMode) {
  17249. mergeLayoutParam(this.option, option, layoutMode);
  17250. }
  17251. },
  17252. // Hooker after init or mergeOption
  17253. optionUpdated: function (newCptOption, isInit) {},
  17254. getDefaultOption: function () {
  17255. var fields = inner$1(this);
  17256. if (!fields.defaultOption) {
  17257. var optList = [];
  17258. var Class = this.constructor;
  17259. while (Class) {
  17260. var opt = Class.prototype.defaultOption;
  17261. opt && optList.push(opt);
  17262. Class = Class.superClass;
  17263. }
  17264. var defaultOption = {};
  17265. for (var i = optList.length - 1; i >= 0; i--) {
  17266. defaultOption = merge(defaultOption, optList[i], true);
  17267. }
  17268. fields.defaultOption = defaultOption;
  17269. }
  17270. return fields.defaultOption;
  17271. },
  17272. getReferringComponents: function (mainType) {
  17273. return this.ecModel.queryComponents({
  17274. mainType: mainType,
  17275. index: this.get(mainType + 'Index', true),
  17276. id: this.get(mainType + 'Id', true)
  17277. });
  17278. }
  17279. });
  17280. // Reset ComponentModel.extend, add preConstruct.
  17281. // clazzUtil.enableClassExtend(
  17282. // ComponentModel,
  17283. // function (option, parentModel, ecModel, extraOpt) {
  17284. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  17285. // zrUtil.extend(this, extraOpt);
  17286. // this.uid = componentUtil.getUID('componentModel');
  17287. // // this.setReadOnly([
  17288. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  17289. // // 'dependentModels', 'componentIndex'
  17290. // // ]);
  17291. // }
  17292. // );
  17293. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  17294. enableClassManagement(
  17295. ComponentModel, {registerWhenExtend: true}
  17296. );
  17297. enableSubTypeDefaulter(ComponentModel);
  17298. // Add capability of ComponentModel.topologicalTravel.
  17299. enableTopologicalTravel(ComponentModel, getDependencies);
  17300. function getDependencies(componentType) {
  17301. var deps = [];
  17302. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  17303. deps = deps.concat(Clazz.prototype.dependencies || []);
  17304. });
  17305. // Ensure main type.
  17306. deps = map(deps, function (type) {
  17307. return parseClassType$1(type).main;
  17308. });
  17309. // Hack dataset for convenience.
  17310. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  17311. deps.unshift('dataset');
  17312. }
  17313. return deps;
  17314. }
  17315. mixin(ComponentModel, boxLayoutMixin);
  17316. /*
  17317. * Licensed to the Apache Software Foundation (ASF) under one
  17318. * or more contributor license agreements. See the NOTICE file
  17319. * distributed with this work for additional information
  17320. * regarding copyright ownership. The ASF licenses this file
  17321. * to you under the Apache License, Version 2.0 (the
  17322. * "License"); you may not use this file except in compliance
  17323. * with the License. You may obtain a copy of the License at
  17324. *
  17325. * http://www.apache.org/licenses/LICENSE-2.0
  17326. *
  17327. * Unless required by applicable law or agreed to in writing,
  17328. * software distributed under the License is distributed on an
  17329. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17330. * KIND, either express or implied. See the License for the
  17331. * specific language governing permissions and limitations
  17332. * under the License.
  17333. */
  17334. var platform = '';
  17335. // Navigator not exists in node
  17336. if (typeof navigator !== 'undefined') {
  17337. platform = navigator.platform || '';
  17338. }
  17339. var globalDefault = {
  17340. // backgroundColor: 'rgba(0,0,0,0)',
  17341. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  17342. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  17343. // Light colors:
  17344. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  17345. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  17346. // Dark colors:
  17347. color: [
  17348. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  17349. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  17350. ],
  17351. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  17352. // If xAxis and yAxis declared, grid is created by default.
  17353. // grid: {},
  17354. textStyle: {
  17355. // color: '#000',
  17356. // decoration: 'none',
  17357. // PENDING
  17358. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  17359. // fontFamily: 'Arial, Verdana, sans-serif',
  17360. fontSize: 12,
  17361. fontStyle: 'normal',
  17362. fontWeight: 'normal'
  17363. },
  17364. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  17365. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  17366. // Default is source-over
  17367. blendMode: null,
  17368. animation: 'auto',
  17369. animationDuration: 1000,
  17370. animationDurationUpdate: 300,
  17371. animationEasing: 'exponentialOut',
  17372. animationEasingUpdate: 'cubicOut',
  17373. animationThreshold: 2000,
  17374. // Configuration for progressive/incremental rendering
  17375. progressiveThreshold: 3000,
  17376. progressive: 400,
  17377. // Threshold of if use single hover layer to optimize.
  17378. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  17379. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  17380. // which is unexpected.
  17381. // see example <echarts/test/heatmap-large.html>.
  17382. hoverLayerThreshold: 3000,
  17383. // See: module:echarts/scale/Time
  17384. useUTC: false
  17385. };
  17386. /*
  17387. * Licensed to the Apache Software Foundation (ASF) under one
  17388. * or more contributor license agreements. See the NOTICE file
  17389. * distributed with this work for additional information
  17390. * regarding copyright ownership. The ASF licenses this file
  17391. * to you under the Apache License, Version 2.0 (the
  17392. * "License"); you may not use this file except in compliance
  17393. * with the License. You may obtain a copy of the License at
  17394. *
  17395. * http://www.apache.org/licenses/LICENSE-2.0
  17396. *
  17397. * Unless required by applicable law or agreed to in writing,
  17398. * software distributed under the License is distributed on an
  17399. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17400. * KIND, either express or implied. See the License for the
  17401. * specific language governing permissions and limitations
  17402. * under the License.
  17403. */
  17404. var inner$2 = makeInner();
  17405. function getNearestColorPalette(colors, requestColorNum) {
  17406. var paletteNum = colors.length;
  17407. // TODO colors must be in order
  17408. for (var i = 0; i < paletteNum; i++) {
  17409. if (colors[i].length > requestColorNum) {
  17410. return colors[i];
  17411. }
  17412. }
  17413. return colors[paletteNum - 1];
  17414. }
  17415. var colorPaletteMixin = {
  17416. clearColorPalette: function () {
  17417. inner$2(this).colorIdx = 0;
  17418. inner$2(this).colorNameMap = {};
  17419. },
  17420. /**
  17421. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  17422. * twise with the same parameters will get different result.
  17423. * @param {Object} [scope=this]
  17424. * @param {Object} [requestColorNum]
  17425. * @return {string} color string.
  17426. */
  17427. getColorFromPalette: function (name, scope, requestColorNum) {
  17428. scope = scope || this;
  17429. var scopeFields = inner$2(scope);
  17430. var colorIdx = scopeFields.colorIdx || 0;
  17431. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  17432. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17433. if (colorNameMap.hasOwnProperty(name)) {
  17434. return colorNameMap[name];
  17435. }
  17436. var defaultColorPalette = normalizeToArray(this.get('color', true));
  17437. var layeredColorPalette = this.get('colorLayer', true);
  17438. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  17439. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  17440. // In case can't find in layered color palette.
  17441. colorPalette = colorPalette || defaultColorPalette;
  17442. if (!colorPalette || !colorPalette.length) {
  17443. return;
  17444. }
  17445. var color = colorPalette[colorIdx];
  17446. if (name) {
  17447. colorNameMap[name] = color;
  17448. }
  17449. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  17450. return color;
  17451. }
  17452. };
  17453. /*
  17454. * Licensed to the Apache Software Foundation (ASF) under one
  17455. * or more contributor license agreements. See the NOTICE file
  17456. * distributed with this work for additional information
  17457. * regarding copyright ownership. The ASF licenses this file
  17458. * to you under the Apache License, Version 2.0 (the
  17459. * "License"); you may not use this file except in compliance
  17460. * with the License. You may obtain a copy of the License at
  17461. *
  17462. * http://www.apache.org/licenses/LICENSE-2.0
  17463. *
  17464. * Unless required by applicable law or agreed to in writing,
  17465. * software distributed under the License is distributed on an
  17466. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17467. * KIND, either express or implied. See the License for the
  17468. * specific language governing permissions and limitations
  17469. * under the License.
  17470. */
  17471. /**
  17472. * Helper for model references.
  17473. * There are many manners to refer axis/coordSys.
  17474. */
  17475. // TODO
  17476. // merge relevant logic to this file?
  17477. // check: "modelHelper" of tooltip and "BrushTargetManager".
  17478. /**
  17479. * @return {Object} For example:
  17480. * {
  17481. * coordSysName: 'cartesian2d',
  17482. * coordSysDims: ['x', 'y', ...],
  17483. * axisMap: HashMap({
  17484. * x: xAxisModel,
  17485. * y: yAxisModel
  17486. * }),
  17487. * categoryAxisMap: HashMap({
  17488. * x: xAxisModel,
  17489. * y: undefined
  17490. * }),
  17491. * // It also indicate that whether there is category axis.
  17492. * firstCategoryDimIndex: 1,
  17493. * // To replace user specified encode.
  17494. * }
  17495. */
  17496. function getCoordSysDefineBySeries(seriesModel) {
  17497. var coordSysName = seriesModel.get('coordinateSystem');
  17498. var result = {
  17499. coordSysName: coordSysName,
  17500. coordSysDims: [],
  17501. axisMap: createHashMap(),
  17502. categoryAxisMap: createHashMap()
  17503. };
  17504. var fetch = fetchers[coordSysName];
  17505. if (fetch) {
  17506. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  17507. return result;
  17508. }
  17509. }
  17510. var fetchers = {
  17511. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  17512. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  17513. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  17514. if (__DEV__) {
  17515. if (!xAxisModel) {
  17516. throw new Error('xAxis "' + retrieve(
  17517. seriesModel.get('xAxisIndex'),
  17518. seriesModel.get('xAxisId'),
  17519. 0
  17520. ) + '" not found');
  17521. }
  17522. if (!yAxisModel) {
  17523. throw new Error('yAxis "' + retrieve(
  17524. seriesModel.get('xAxisIndex'),
  17525. seriesModel.get('yAxisId'),
  17526. 0
  17527. ) + '" not found');
  17528. }
  17529. }
  17530. result.coordSysDims = ['x', 'y'];
  17531. axisMap.set('x', xAxisModel);
  17532. axisMap.set('y', yAxisModel);
  17533. if (isCategory(xAxisModel)) {
  17534. categoryAxisMap.set('x', xAxisModel);
  17535. result.firstCategoryDimIndex = 0;
  17536. }
  17537. if (isCategory(yAxisModel)) {
  17538. categoryAxisMap.set('y', yAxisModel);
  17539. result.firstCategoryDimIndex = 1;
  17540. }
  17541. },
  17542. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  17543. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  17544. if (__DEV__) {
  17545. if (!singleAxisModel) {
  17546. throw new Error('singleAxis should be specified.');
  17547. }
  17548. }
  17549. result.coordSysDims = ['single'];
  17550. axisMap.set('single', singleAxisModel);
  17551. if (isCategory(singleAxisModel)) {
  17552. categoryAxisMap.set('single', singleAxisModel);
  17553. result.firstCategoryDimIndex = 0;
  17554. }
  17555. },
  17556. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  17557. var polarModel = seriesModel.getReferringComponents('polar')[0];
  17558. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  17559. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  17560. if (__DEV__) {
  17561. if (!angleAxisModel) {
  17562. throw new Error('angleAxis option not found');
  17563. }
  17564. if (!radiusAxisModel) {
  17565. throw new Error('radiusAxis option not found');
  17566. }
  17567. }
  17568. result.coordSysDims = ['radius', 'angle'];
  17569. axisMap.set('radius', radiusAxisModel);
  17570. axisMap.set('angle', angleAxisModel);
  17571. if (isCategory(radiusAxisModel)) {
  17572. categoryAxisMap.set('radius', radiusAxisModel);
  17573. result.firstCategoryDimIndex = 0;
  17574. }
  17575. if (isCategory(angleAxisModel)) {
  17576. categoryAxisMap.set('angle', angleAxisModel);
  17577. result.firstCategoryDimIndex = 1;
  17578. }
  17579. },
  17580. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  17581. result.coordSysDims = ['lng', 'lat'];
  17582. },
  17583. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  17584. var ecModel = seriesModel.ecModel;
  17585. var parallelModel = ecModel.getComponent(
  17586. 'parallel', seriesModel.get('parallelIndex')
  17587. );
  17588. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  17589. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  17590. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  17591. var axisDim = coordSysDims[index];
  17592. axisMap.set(axisDim, axisModel);
  17593. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  17594. categoryAxisMap.set(axisDim, axisModel);
  17595. result.firstCategoryDimIndex = index;
  17596. }
  17597. });
  17598. }
  17599. };
  17600. function isCategory(axisModel) {
  17601. return axisModel.get('type') === 'category';
  17602. }
  17603. /*
  17604. * Licensed to the Apache Software Foundation (ASF) under one
  17605. * or more contributor license agreements. See the NOTICE file
  17606. * distributed with this work for additional information
  17607. * regarding copyright ownership. The ASF licenses this file
  17608. * to you under the Apache License, Version 2.0 (the
  17609. * "License"); you may not use this file except in compliance
  17610. * with the License. You may obtain a copy of the License at
  17611. *
  17612. * http://www.apache.org/licenses/LICENSE-2.0
  17613. *
  17614. * Unless required by applicable law or agreed to in writing,
  17615. * software distributed under the License is distributed on an
  17616. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17617. * KIND, either express or implied. See the License for the
  17618. * specific language governing permissions and limitations
  17619. * under the License.
  17620. */
  17621. // Avoid typo.
  17622. var SOURCE_FORMAT_ORIGINAL = 'original';
  17623. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  17624. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  17625. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  17626. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  17627. // ??? CHANGE A NAME
  17628. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  17629. var SERIES_LAYOUT_BY_COLUMN = 'column';
  17630. var SERIES_LAYOUT_BY_ROW = 'row';
  17631. /*
  17632. * Licensed to the Apache Software Foundation (ASF) under one
  17633. * or more contributor license agreements. See the NOTICE file
  17634. * distributed with this work for additional information
  17635. * regarding copyright ownership. The ASF licenses this file
  17636. * to you under the Apache License, Version 2.0 (the
  17637. * "License"); you may not use this file except in compliance
  17638. * with the License. You may obtain a copy of the License at
  17639. *
  17640. * http://www.apache.org/licenses/LICENSE-2.0
  17641. *
  17642. * Unless required by applicable law or agreed to in writing,
  17643. * software distributed under the License is distributed on an
  17644. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17645. * KIND, either express or implied. See the License for the
  17646. * specific language governing permissions and limitations
  17647. * under the License.
  17648. */
  17649. /**
  17650. * [sourceFormat]
  17651. *
  17652. * + "original":
  17653. * This format is only used in series.data, where
  17654. * itemStyle can be specified in data item.
  17655. *
  17656. * + "arrayRows":
  17657. * [
  17658. * ['product', 'score', 'amount'],
  17659. * ['Matcha Latte', 89.3, 95.8],
  17660. * ['Milk Tea', 92.1, 89.4],
  17661. * ['Cheese Cocoa', 94.4, 91.2],
  17662. * ['Walnut Brownie', 85.4, 76.9]
  17663. * ]
  17664. *
  17665. * + "objectRows":
  17666. * [
  17667. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  17668. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  17669. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  17670. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  17671. * ]
  17672. *
  17673. * + "keyedColumns":
  17674. * {
  17675. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  17676. * 'count': [823, 235, 1042, 988],
  17677. * 'score': [95.8, 81.4, 91.2, 76.9]
  17678. * }
  17679. *
  17680. * + "typedArray"
  17681. *
  17682. * + "unknown"
  17683. */
  17684. /**
  17685. * @constructor
  17686. * @param {Object} fields
  17687. * @param {string} fields.sourceFormat
  17688. * @param {Array|Object} fields.fromDataset
  17689. * @param {Array|Object} [fields.data]
  17690. * @param {string} [seriesLayoutBy='column']
  17691. * @param {Array.<Object|string>} [dimensionsDefine]
  17692. * @param {Objet|HashMap} [encodeDefine]
  17693. * @param {number} [startIndex=0]
  17694. * @param {number} [dimensionsDetectCount]
  17695. */
  17696. function Source(fields) {
  17697. /**
  17698. * @type {boolean}
  17699. */
  17700. this.fromDataset = fields.fromDataset;
  17701. /**
  17702. * Not null/undefined.
  17703. * @type {Array|Object}
  17704. */
  17705. this.data = fields.data || (
  17706. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  17707. );
  17708. /**
  17709. * See also "detectSourceFormat".
  17710. * Not null/undefined.
  17711. * @type {string}
  17712. */
  17713. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  17714. /**
  17715. * 'row' or 'column'
  17716. * Not null/undefined.
  17717. * @type {string} seriesLayoutBy
  17718. */
  17719. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  17720. /**
  17721. * dimensions definition in option.
  17722. * can be null/undefined.
  17723. * @type {Array.<Object|string>}
  17724. */
  17725. this.dimensionsDefine = fields.dimensionsDefine;
  17726. /**
  17727. * encode definition in option.
  17728. * can be null/undefined.
  17729. * @type {Objet|HashMap}
  17730. */
  17731. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  17732. /**
  17733. * Not null/undefined, uint.
  17734. * @type {number}
  17735. */
  17736. this.startIndex = fields.startIndex || 0;
  17737. /**
  17738. * Can be null/undefined (when unknown), uint.
  17739. * @type {number}
  17740. */
  17741. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  17742. }
  17743. /**
  17744. * Wrap original series data for some compatibility cases.
  17745. */
  17746. Source.seriesDataToSource = function (data) {
  17747. return new Source({
  17748. data: data,
  17749. sourceFormat: isTypedArray(data)
  17750. ? SOURCE_FORMAT_TYPED_ARRAY
  17751. : SOURCE_FORMAT_ORIGINAL,
  17752. fromDataset: false
  17753. });
  17754. };
  17755. enableClassCheck(Source);
  17756. /*
  17757. * Licensed to the Apache Software Foundation (ASF) under one
  17758. * or more contributor license agreements. See the NOTICE file
  17759. * distributed with this work for additional information
  17760. * regarding copyright ownership. The ASF licenses this file
  17761. * to you under the Apache License, Version 2.0 (the
  17762. * "License"); you may not use this file except in compliance
  17763. * with the License. You may obtain a copy of the License at
  17764. *
  17765. * http://www.apache.org/licenses/LICENSE-2.0
  17766. *
  17767. * Unless required by applicable law or agreed to in writing,
  17768. * software distributed under the License is distributed on an
  17769. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17770. * KIND, either express or implied. See the License for the
  17771. * specific language governing permissions and limitations
  17772. * under the License.
  17773. */
  17774. var inner$3 = makeInner();
  17775. /**
  17776. * @see {module:echarts/data/Source}
  17777. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17778. * @return {string} sourceFormat
  17779. */
  17780. function detectSourceFormat(datasetModel) {
  17781. var data = datasetModel.option.source;
  17782. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17783. if (isTypedArray(data)) {
  17784. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17785. }
  17786. else if (isArray(data)) {
  17787. // FIXME Whether tolerate null in top level array?
  17788. if (data.length === 0) {
  17789. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17790. }
  17791. for (var i = 0, len = data.length; i < len; i++) {
  17792. var item = data[i];
  17793. if (item == null) {
  17794. continue;
  17795. }
  17796. else if (isArray(item)) {
  17797. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17798. break;
  17799. }
  17800. else if (isObject$1(item)) {
  17801. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17802. break;
  17803. }
  17804. }
  17805. }
  17806. else if (isObject$1(data)) {
  17807. for (var key in data) {
  17808. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17809. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17810. break;
  17811. }
  17812. }
  17813. }
  17814. else if (data != null) {
  17815. throw new Error('Invalid data');
  17816. }
  17817. inner$3(datasetModel).sourceFormat = sourceFormat;
  17818. }
  17819. /**
  17820. * [Scenarios]:
  17821. * (1) Provide source data directly:
  17822. * series: {
  17823. * encode: {...},
  17824. * dimensions: [...]
  17825. * seriesLayoutBy: 'row',
  17826. * data: [[...]]
  17827. * }
  17828. * (2) Refer to datasetModel.
  17829. * series: [{
  17830. * encode: {...}
  17831. * // Ignore datasetIndex means `datasetIndex: 0`
  17832. * // and the dimensions defination in dataset is used
  17833. * }, {
  17834. * encode: {...},
  17835. * seriesLayoutBy: 'column',
  17836. * datasetIndex: 1
  17837. * }]
  17838. *
  17839. * Get data from series itself or datset.
  17840. * @return {module:echarts/data/Source} source
  17841. */
  17842. function getSource(seriesModel) {
  17843. return inner$3(seriesModel).source;
  17844. }
  17845. /**
  17846. * MUST be called before mergeOption of all series.
  17847. * @param {module:echarts/model/Global} ecModel
  17848. */
  17849. function resetSourceDefaulter(ecModel) {
  17850. // `datasetMap` is used to make default encode.
  17851. inner$3(ecModel).datasetMap = createHashMap();
  17852. }
  17853. /**
  17854. * [Caution]:
  17855. * MUST be called after series option merged and
  17856. * before "series.getInitailData()" called.
  17857. *
  17858. * [The rule of making default encode]:
  17859. * Category axis (if exists) alway map to the first dimension.
  17860. * Each other axis occupies a subsequent dimension.
  17861. *
  17862. * [Why make default encode]:
  17863. * Simplify the typing of encode in option, avoiding the case like that:
  17864. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17865. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17866. *
  17867. * @param {module:echarts/model/Series} seriesModel
  17868. */
  17869. function prepareSource(seriesModel) {
  17870. var seriesOption = seriesModel.option;
  17871. var data = seriesOption.data;
  17872. var sourceFormat = isTypedArray(data)
  17873. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17874. var fromDataset = false;
  17875. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  17876. var sourceHeader = seriesOption.sourceHeader;
  17877. var dimensionsDefine = seriesOption.dimensions;
  17878. var datasetModel = getDatasetModel(seriesModel);
  17879. if (datasetModel) {
  17880. var datasetOption = datasetModel.option;
  17881. data = datasetOption.source;
  17882. sourceFormat = inner$3(datasetModel).sourceFormat;
  17883. fromDataset = true;
  17884. // These settings from series has higher priority.
  17885. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  17886. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  17887. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  17888. }
  17889. var completeResult = completeBySourceData(
  17890. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  17891. );
  17892. // Note: dataset option does not have `encode`.
  17893. var encodeDefine = seriesOption.encode;
  17894. if (!encodeDefine && datasetModel) {
  17895. encodeDefine = makeDefaultEncode(
  17896. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17897. );
  17898. }
  17899. inner$3(seriesModel).source = new Source({
  17900. data: data,
  17901. fromDataset: fromDataset,
  17902. seriesLayoutBy: seriesLayoutBy,
  17903. sourceFormat: sourceFormat,
  17904. dimensionsDefine: completeResult.dimensionsDefine,
  17905. startIndex: completeResult.startIndex,
  17906. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  17907. encodeDefine: encodeDefine
  17908. });
  17909. }
  17910. // return {startIndex, dimensionsDefine, dimensionsCount}
  17911. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  17912. if (!data) {
  17913. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  17914. }
  17915. var dimensionsDetectCount;
  17916. var startIndex;
  17917. var findPotentialName;
  17918. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17919. // Rule: Most of the first line are string: it is header.
  17920. // Caution: consider a line with 5 string and 1 number,
  17921. // it still can not be sure it is a head, because the
  17922. // 5 string may be 5 values of category columns.
  17923. if (sourceHeader === 'auto' || sourceHeader == null) {
  17924. arrayRowsTravelFirst(function (val) {
  17925. // '-' is regarded as null/undefined.
  17926. if (val != null && val !== '-') {
  17927. if (isString(val)) {
  17928. startIndex == null && (startIndex = 1);
  17929. }
  17930. else {
  17931. startIndex = 0;
  17932. }
  17933. }
  17934. // 10 is an experience number, avoid long loop.
  17935. }, seriesLayoutBy, data, 10);
  17936. }
  17937. else {
  17938. startIndex = sourceHeader ? 1 : 0;
  17939. }
  17940. if (!dimensionsDefine && startIndex === 1) {
  17941. dimensionsDefine = [];
  17942. arrayRowsTravelFirst(function (val, index) {
  17943. dimensionsDefine[index] = val != null ? val : '';
  17944. }, seriesLayoutBy, data);
  17945. }
  17946. dimensionsDetectCount = dimensionsDefine
  17947. ? dimensionsDefine.length
  17948. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  17949. ? data.length
  17950. : data[0]
  17951. ? data[0].length
  17952. : null;
  17953. }
  17954. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17955. if (!dimensionsDefine) {
  17956. dimensionsDefine = objectRowsCollectDimensions(data);
  17957. findPotentialName = true;
  17958. }
  17959. }
  17960. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17961. if (!dimensionsDefine) {
  17962. dimensionsDefine = [];
  17963. findPotentialName = true;
  17964. each$1(data, function (colArr, key) {
  17965. dimensionsDefine.push(key);
  17966. });
  17967. }
  17968. }
  17969. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17970. var value0 = getDataItemValue(data[0]);
  17971. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  17972. }
  17973. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  17974. if (__DEV__) {
  17975. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  17976. }
  17977. }
  17978. var potentialNameDimIndex;
  17979. if (findPotentialName) {
  17980. each$1(dimensionsDefine, function (dim, idx) {
  17981. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  17982. potentialNameDimIndex = idx;
  17983. }
  17984. });
  17985. }
  17986. return {
  17987. startIndex: startIndex,
  17988. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  17989. dimensionsDetectCount: dimensionsDetectCount,
  17990. potentialNameDimIndex: potentialNameDimIndex
  17991. // TODO: potentialIdDimIdx
  17992. };
  17993. }
  17994. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  17995. // which is reasonable. But dimension name is duplicated.
  17996. // Returns undefined or an array contains only object without null/undefiend or string.
  17997. function normalizeDimensionsDefine(dimensionsDefine) {
  17998. if (!dimensionsDefine) {
  17999. // The meaning of null/undefined is different from empty array.
  18000. return;
  18001. }
  18002. var nameMap = createHashMap();
  18003. return map(dimensionsDefine, function (item, index) {
  18004. item = extend({}, isObject$1(item) ? item : {name: item});
  18005. // User can set null in dimensions.
  18006. // We dont auto specify name, othewise a given name may
  18007. // cause it be refered unexpectedly.
  18008. if (item.name == null) {
  18009. return item;
  18010. }
  18011. // Also consider number form like 2012.
  18012. item.name += '';
  18013. // User may also specify displayName.
  18014. // displayName will always exists except user not
  18015. // specified or dim name is not specified or detected.
  18016. // (A auto generated dim name will not be used as
  18017. // displayName).
  18018. if (item.displayName == null) {
  18019. item.displayName = item.name;
  18020. }
  18021. var exist = nameMap.get(item.name);
  18022. if (!exist) {
  18023. nameMap.set(item.name, {count: 1});
  18024. }
  18025. else {
  18026. item.name += '-' + exist.count++;
  18027. }
  18028. return item;
  18029. });
  18030. }
  18031. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18032. maxLoop == null && (maxLoop = Infinity);
  18033. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18034. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18035. cb(data[i] ? data[i][0] : null, i);
  18036. }
  18037. }
  18038. else {
  18039. var value0 = data[0] || [];
  18040. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18041. cb(value0[i], i);
  18042. }
  18043. }
  18044. }
  18045. function objectRowsCollectDimensions(data) {
  18046. var firstIndex = 0;
  18047. var obj;
  18048. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18049. if (obj) {
  18050. var dimensions = [];
  18051. each$1(obj, function (value, key) {
  18052. dimensions.push(key);
  18053. });
  18054. return dimensions;
  18055. }
  18056. }
  18057. // ??? TODO merge to completedimensions, where also has
  18058. // default encode making logic. And the default rule
  18059. // should depends on series? consider 'map'.
  18060. function makeDefaultEncode(
  18061. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  18062. ) {
  18063. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  18064. var encode = {};
  18065. // var encodeTooltip = [];
  18066. // var encodeLabel = [];
  18067. var encodeItemName = [];
  18068. var encodeSeriesName = [];
  18069. var seriesType = seriesModel.subType;
  18070. // ??? TODO refactor: provide by series itself.
  18071. // Consider the case: 'map' series is based on geo coordSys,
  18072. // 'graph', 'heatmap' can be based on cartesian. But can not
  18073. // give default rule simply here.
  18074. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  18075. var cSeriesMap = createHashMap([
  18076. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  18077. ]);
  18078. // Usually in this case series will use the first data
  18079. // dimension as the "value" dimension, or other default
  18080. // processes respectively.
  18081. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  18082. var ecModel = seriesModel.ecModel;
  18083. var datasetMap = inner$3(ecModel).datasetMap;
  18084. var key = datasetModel.uid + '_' + seriesLayoutBy;
  18085. var datasetRecord = datasetMap.get(key)
  18086. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  18087. // TODO
  18088. // Auto detect first time axis and do arrangement.
  18089. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  18090. // In value way.
  18091. if (coordSysDefine.firstCategoryDimIndex == null) {
  18092. var dataDim = datasetRecord.valueWayDim++;
  18093. encode[coordDim] = dataDim;
  18094. // ??? TODO give a better default series name rule?
  18095. // especially when encode x y specified.
  18096. // consider: when mutiple series share one dimension
  18097. // category axis, series name should better use
  18098. // the other dimsion name. On the other hand, use
  18099. // both dimensions name.
  18100. encodeSeriesName.push(dataDim);
  18101. // encodeTooltip.push(dataDim);
  18102. // encodeLabel.push(dataDim);
  18103. }
  18104. // In category way, category axis.
  18105. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  18106. encode[coordDim] = 0;
  18107. encodeItemName.push(0);
  18108. }
  18109. // In category way, non-category axis.
  18110. else {
  18111. var dataDim = datasetRecord.categoryWayDim++;
  18112. encode[coordDim] = dataDim;
  18113. // encodeTooltip.push(dataDim);
  18114. // encodeLabel.push(dataDim);
  18115. encodeSeriesName.push(dataDim);
  18116. }
  18117. });
  18118. }
  18119. // Do not make a complex rule! Hard to code maintain and not necessary.
  18120. // ??? TODO refactor: provide by series itself.
  18121. // [{name: ..., value: ...}, ...] like:
  18122. else if (nSeriesMap.get(seriesType) != null) {
  18123. // Find the first not ordinal. (5 is an experience value)
  18124. var firstNotOrdinal;
  18125. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  18126. if (!doGuessOrdinal(
  18127. data, sourceFormat, seriesLayoutBy,
  18128. completeResult.dimensionsDefine, completeResult.startIndex, i
  18129. )) {
  18130. firstNotOrdinal = i;
  18131. }
  18132. }
  18133. if (firstNotOrdinal != null) {
  18134. encode.value = firstNotOrdinal;
  18135. var nameDimIndex = completeResult.potentialNameDimIndex
  18136. || Math.max(firstNotOrdinal - 1, 0);
  18137. // By default, label use itemName in charts.
  18138. // So we dont set encodeLabel here.
  18139. encodeSeriesName.push(nameDimIndex);
  18140. encodeItemName.push(nameDimIndex);
  18141. // encodeTooltip.push(firstNotOrdinal);
  18142. }
  18143. }
  18144. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  18145. // encodeLabel.length && (encode.label = encodeLabel);
  18146. encodeItemName.length && (encode.itemName = encodeItemName);
  18147. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18148. return encode;
  18149. }
  18150. /**
  18151. * If return null/undefined, indicate that should not use datasetModel.
  18152. */
  18153. function getDatasetModel(seriesModel) {
  18154. var option = seriesModel.option;
  18155. // Caution: consider the scenario:
  18156. // A dataset is declared and a series is not expected to use the dataset,
  18157. // and at the beginning `setOption({series: { noData })` (just prepare other
  18158. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18159. // the user should set an empty array to avoid that dataset is used by default.
  18160. var thisData = option.data;
  18161. if (!thisData) {
  18162. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  18163. }
  18164. }
  18165. /**
  18166. * The rule should not be complex, otherwise user might not
  18167. * be able to known where the data is wrong.
  18168. * The code is ugly, but how to make it neat?
  18169. *
  18170. * @param {module:echars/data/Source} source
  18171. * @param {number} dimIndex
  18172. * @return {boolean} Whether ordinal.
  18173. */
  18174. function guessOrdinal(source, dimIndex) {
  18175. return doGuessOrdinal(
  18176. source.data,
  18177. source.sourceFormat,
  18178. source.seriesLayoutBy,
  18179. source.dimensionsDefine,
  18180. source.startIndex,
  18181. dimIndex
  18182. );
  18183. }
  18184. // dimIndex may be overflow source data.
  18185. function doGuessOrdinal(
  18186. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  18187. ) {
  18188. var result;
  18189. // Experience value.
  18190. var maxLoop = 5;
  18191. if (isTypedArray(data)) {
  18192. return false;
  18193. }
  18194. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  18195. // always exists in source.
  18196. var dimName;
  18197. if (dimensionsDefine) {
  18198. dimName = dimensionsDefine[dimIndex];
  18199. dimName = isObject$1(dimName) ? dimName.name : dimName;
  18200. }
  18201. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18202. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18203. var sample = data[dimIndex];
  18204. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  18205. if ((result = detectValue(sample[startIndex + i])) != null) {
  18206. return result;
  18207. }
  18208. }
  18209. }
  18210. else {
  18211. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18212. var row = data[startIndex + i];
  18213. if (row && (result = detectValue(row[dimIndex])) != null) {
  18214. return result;
  18215. }
  18216. }
  18217. }
  18218. }
  18219. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18220. if (!dimName) {
  18221. return;
  18222. }
  18223. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18224. var item = data[i];
  18225. if (item && (result = detectValue(item[dimName])) != null) {
  18226. return result;
  18227. }
  18228. }
  18229. }
  18230. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18231. if (!dimName) {
  18232. return;
  18233. }
  18234. var sample = data[dimName];
  18235. if (!sample || isTypedArray(sample)) {
  18236. return false;
  18237. }
  18238. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  18239. if ((result = detectValue(sample[i])) != null) {
  18240. return result;
  18241. }
  18242. }
  18243. }
  18244. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18245. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18246. var item = data[i];
  18247. var val = getDataItemValue(item);
  18248. if (!isArray(val)) {
  18249. return false;
  18250. }
  18251. if ((result = detectValue(val[dimIndex])) != null) {
  18252. return result;
  18253. }
  18254. }
  18255. }
  18256. function detectValue(val) {
  18257. // Consider usage convenience, '1', '2' will be treated as "number".
  18258. // `isFinit('')` get `true`.
  18259. if (val != null && isFinite(val) && val !== '') {
  18260. return false;
  18261. }
  18262. else if (isString(val) && val !== '-') {
  18263. return true;
  18264. }
  18265. }
  18266. return false;
  18267. }
  18268. /*
  18269. * Licensed to the Apache Software Foundation (ASF) under one
  18270. * or more contributor license agreements. See the NOTICE file
  18271. * distributed with this work for additional information
  18272. * regarding copyright ownership. The ASF licenses this file
  18273. * to you under the Apache License, Version 2.0 (the
  18274. * "License"); you may not use this file except in compliance
  18275. * with the License. You may obtain a copy of the License at
  18276. *
  18277. * http://www.apache.org/licenses/LICENSE-2.0
  18278. *
  18279. * Unless required by applicable law or agreed to in writing,
  18280. * software distributed under the License is distributed on an
  18281. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18282. * KIND, either express or implied. See the License for the
  18283. * specific language governing permissions and limitations
  18284. * under the License.
  18285. */
  18286. /**
  18287. * ECharts global model
  18288. *
  18289. * @module {echarts/model/Global}
  18290. */
  18291. /**
  18292. * Caution: If the mechanism should be changed some day, these cases
  18293. * should be considered:
  18294. *
  18295. * (1) In `merge option` mode, if using the same option to call `setOption`
  18296. * many times, the result should be the same (try our best to ensure that).
  18297. * (2) In `merge option` mode, if a component has no id/name specified, it
  18298. * will be merged by index, and the result sequence of the components is
  18299. * consistent to the original sequence.
  18300. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  18301. * `mergeOption` in module:echarts/model/OptionManager.
  18302. */
  18303. var OPTION_INNER_KEY = '\0_ec_inner';
  18304. /**
  18305. * @alias module:echarts/model/Global
  18306. *
  18307. * @param {Object} option
  18308. * @param {module:echarts/model/Model} parentModel
  18309. * @param {Object} theme
  18310. */
  18311. var GlobalModel = Model.extend({
  18312. init: function (option, parentModel, theme, optionManager) {
  18313. theme = theme || {};
  18314. this.option = null; // Mark as not initialized.
  18315. /**
  18316. * @type {module:echarts/model/Model}
  18317. * @private
  18318. */
  18319. this._theme = new Model(theme);
  18320. /**
  18321. * @type {module:echarts/model/OptionManager}
  18322. */
  18323. this._optionManager = optionManager;
  18324. },
  18325. setOption: function (option, optionPreprocessorFuncs) {
  18326. assert$1(
  18327. !(OPTION_INNER_KEY in option),
  18328. 'please use chart.getOption()'
  18329. );
  18330. this._optionManager.setOption(option, optionPreprocessorFuncs);
  18331. this.resetOption(null);
  18332. },
  18333. /**
  18334. * @param {string} type null/undefined: reset all.
  18335. * 'recreate': force recreate all.
  18336. * 'timeline': only reset timeline option
  18337. * 'media': only reset media query option
  18338. * @return {boolean} Whether option changed.
  18339. */
  18340. resetOption: function (type) {
  18341. var optionChanged = false;
  18342. var optionManager = this._optionManager;
  18343. if (!type || type === 'recreate') {
  18344. var baseOption = optionManager.mountOption(type === 'recreate');
  18345. if (!this.option || type === 'recreate') {
  18346. initBase.call(this, baseOption);
  18347. }
  18348. else {
  18349. this.restoreData();
  18350. this.mergeOption(baseOption);
  18351. }
  18352. optionChanged = true;
  18353. }
  18354. if (type === 'timeline' || type === 'media') {
  18355. this.restoreData();
  18356. }
  18357. if (!type || type === 'recreate' || type === 'timeline') {
  18358. var timelineOption = optionManager.getTimelineOption(this);
  18359. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  18360. }
  18361. if (!type || type === 'recreate' || type === 'media') {
  18362. var mediaOptions = optionManager.getMediaOption(this, this._api);
  18363. if (mediaOptions.length) {
  18364. each$1(mediaOptions, function (mediaOption) {
  18365. this.mergeOption(mediaOption, optionChanged = true);
  18366. }, this);
  18367. }
  18368. }
  18369. return optionChanged;
  18370. },
  18371. /**
  18372. * @protected
  18373. */
  18374. mergeOption: function (newOption) {
  18375. var option = this.option;
  18376. var componentsMap = this._componentsMap;
  18377. var newCptTypes = [];
  18378. resetSourceDefaulter(this);
  18379. // If no component class, merge directly.
  18380. // For example: color, animaiton options, etc.
  18381. each$1(newOption, function (componentOption, mainType) {
  18382. if (componentOption == null) {
  18383. return;
  18384. }
  18385. if (!ComponentModel.hasClass(mainType)) {
  18386. // globalSettingTask.dirty();
  18387. option[mainType] = option[mainType] == null
  18388. ? clone(componentOption)
  18389. : merge(option[mainType], componentOption, true);
  18390. }
  18391. else if (mainType) {
  18392. newCptTypes.push(mainType);
  18393. }
  18394. });
  18395. ComponentModel.topologicalTravel(
  18396. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  18397. );
  18398. function visitComponent(mainType, dependencies) {
  18399. var newCptOptionList = normalizeToArray(newOption[mainType]);
  18400. var mapResult = mappingToExists(
  18401. componentsMap.get(mainType), newCptOptionList
  18402. );
  18403. makeIdAndName(mapResult);
  18404. // Set mainType and complete subType.
  18405. each$1(mapResult, function (item, index) {
  18406. var opt = item.option;
  18407. if (isObject$1(opt)) {
  18408. item.keyInfo.mainType = mainType;
  18409. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  18410. }
  18411. });
  18412. var dependentModels = getComponentsByTypes(
  18413. componentsMap, dependencies
  18414. );
  18415. option[mainType] = [];
  18416. componentsMap.set(mainType, []);
  18417. each$1(mapResult, function (resultItem, index) {
  18418. var componentModel = resultItem.exist;
  18419. var newCptOption = resultItem.option;
  18420. assert$1(
  18421. isObject$1(newCptOption) || componentModel,
  18422. 'Empty component definition'
  18423. );
  18424. // Consider where is no new option and should be merged using {},
  18425. // see removeEdgeAndAdd in topologicalTravel and
  18426. // ComponentModel.getAllClassMainTypes.
  18427. if (!newCptOption) {
  18428. componentModel.mergeOption({}, this);
  18429. componentModel.optionUpdated({}, false);
  18430. }
  18431. else {
  18432. var ComponentModelClass = ComponentModel.getClass(
  18433. mainType, resultItem.keyInfo.subType, true
  18434. );
  18435. if (componentModel && componentModel instanceof ComponentModelClass) {
  18436. componentModel.name = resultItem.keyInfo.name;
  18437. // componentModel.settingTask && componentModel.settingTask.dirty();
  18438. componentModel.mergeOption(newCptOption, this);
  18439. componentModel.optionUpdated(newCptOption, false);
  18440. }
  18441. else {
  18442. // PENDING Global as parent ?
  18443. var extraOpt = extend(
  18444. {
  18445. dependentModels: dependentModels,
  18446. componentIndex: index
  18447. },
  18448. resultItem.keyInfo
  18449. );
  18450. componentModel = new ComponentModelClass(
  18451. newCptOption, this, this, extraOpt
  18452. );
  18453. extend(componentModel, extraOpt);
  18454. componentModel.init(newCptOption, this, this, extraOpt);
  18455. // Call optionUpdated after init.
  18456. // newCptOption has been used as componentModel.option
  18457. // and may be merged with theme and default, so pass null
  18458. // to avoid confusion.
  18459. componentModel.optionUpdated(null, true);
  18460. }
  18461. }
  18462. componentsMap.get(mainType)[index] = componentModel;
  18463. option[mainType][index] = componentModel.option;
  18464. }, this);
  18465. // Backup series for filtering.
  18466. if (mainType === 'series') {
  18467. createSeriesIndices(this, componentsMap.get('series'));
  18468. }
  18469. }
  18470. this._seriesIndicesMap = createHashMap(
  18471. this._seriesIndices = this._seriesIndices || []
  18472. );
  18473. },
  18474. /**
  18475. * Get option for output (cloned option and inner info removed)
  18476. * @public
  18477. * @return {Object}
  18478. */
  18479. getOption: function () {
  18480. var option = clone(this.option);
  18481. each$1(option, function (opts, mainType) {
  18482. if (ComponentModel.hasClass(mainType)) {
  18483. var opts = normalizeToArray(opts);
  18484. for (var i = opts.length - 1; i >= 0; i--) {
  18485. // Remove options with inner id.
  18486. if (isIdInner(opts[i])) {
  18487. opts.splice(i, 1);
  18488. }
  18489. }
  18490. option[mainType] = opts;
  18491. }
  18492. });
  18493. delete option[OPTION_INNER_KEY];
  18494. return option;
  18495. },
  18496. /**
  18497. * @return {module:echarts/model/Model}
  18498. */
  18499. getTheme: function () {
  18500. return this._theme;
  18501. },
  18502. /**
  18503. * @param {string} mainType
  18504. * @param {number} [idx=0]
  18505. * @return {module:echarts/model/Component}
  18506. */
  18507. getComponent: function (mainType, idx) {
  18508. var list = this._componentsMap.get(mainType);
  18509. if (list) {
  18510. return list[idx || 0];
  18511. }
  18512. },
  18513. /**
  18514. * If none of index and id and name used, return all components with mainType.
  18515. * @param {Object} condition
  18516. * @param {string} condition.mainType
  18517. * @param {string} [condition.subType] If ignore, only query by mainType
  18518. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  18519. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  18520. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  18521. * @return {Array.<module:echarts/model/Component>}
  18522. */
  18523. queryComponents: function (condition) {
  18524. var mainType = condition.mainType;
  18525. if (!mainType) {
  18526. return [];
  18527. }
  18528. var index = condition.index;
  18529. var id = condition.id;
  18530. var name = condition.name;
  18531. var cpts = this._componentsMap.get(mainType);
  18532. if (!cpts || !cpts.length) {
  18533. return [];
  18534. }
  18535. var result;
  18536. if (index != null) {
  18537. if (!isArray(index)) {
  18538. index = [index];
  18539. }
  18540. result = filter(map(index, function (idx) {
  18541. return cpts[idx];
  18542. }), function (val) {
  18543. return !!val;
  18544. });
  18545. }
  18546. else if (id != null) {
  18547. var isIdArray = isArray(id);
  18548. result = filter(cpts, function (cpt) {
  18549. return (isIdArray && indexOf(id, cpt.id) >= 0)
  18550. || (!isIdArray && cpt.id === id);
  18551. });
  18552. }
  18553. else if (name != null) {
  18554. var isNameArray = isArray(name);
  18555. result = filter(cpts, function (cpt) {
  18556. return (isNameArray && indexOf(name, cpt.name) >= 0)
  18557. || (!isNameArray && cpt.name === name);
  18558. });
  18559. }
  18560. else {
  18561. // Return all components with mainType
  18562. result = cpts.slice();
  18563. }
  18564. return filterBySubType(result, condition);
  18565. },
  18566. /**
  18567. * The interface is different from queryComponents,
  18568. * which is convenient for inner usage.
  18569. *
  18570. * @usage
  18571. * var result = findComponents(
  18572. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  18573. * );
  18574. * var result = findComponents(
  18575. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  18576. * );
  18577. * var result = findComponents(
  18578. * {mainType: 'series'},
  18579. * function (model, index) {...}
  18580. * );
  18581. * // result like [component0, componnet1, ...]
  18582. *
  18583. * @param {Object} condition
  18584. * @param {string} condition.mainType Mandatory.
  18585. * @param {string} [condition.subType] Optional.
  18586. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  18587. * where xxx is mainType.
  18588. * If query attribute is null/undefined or has no index/id/name,
  18589. * do not filtering by query conditions, which is convenient for
  18590. * no-payload situations or when target of action is global.
  18591. * @param {Function} [condition.filter] parameter: component, return boolean.
  18592. * @return {Array.<module:echarts/model/Component>}
  18593. */
  18594. findComponents: function (condition) {
  18595. var query = condition.query;
  18596. var mainType = condition.mainType;
  18597. var queryCond = getQueryCond(query);
  18598. var result = queryCond
  18599. ? this.queryComponents(queryCond)
  18600. : this._componentsMap.get(mainType);
  18601. return doFilter(filterBySubType(result, condition));
  18602. function getQueryCond(q) {
  18603. var indexAttr = mainType + 'Index';
  18604. var idAttr = mainType + 'Id';
  18605. var nameAttr = mainType + 'Name';
  18606. return q && (
  18607. q[indexAttr] != null
  18608. || q[idAttr] != null
  18609. || q[nameAttr] != null
  18610. )
  18611. ? {
  18612. mainType: mainType,
  18613. // subType will be filtered finally.
  18614. index: q[indexAttr],
  18615. id: q[idAttr],
  18616. name: q[nameAttr]
  18617. }
  18618. : null;
  18619. }
  18620. function doFilter(res) {
  18621. return condition.filter
  18622. ? filter(res, condition.filter)
  18623. : res;
  18624. }
  18625. },
  18626. /**
  18627. * @usage
  18628. * eachComponent('legend', function (legendModel, index) {
  18629. * ...
  18630. * });
  18631. * eachComponent(function (componentType, model, index) {
  18632. * // componentType does not include subType
  18633. * // (componentType is 'xxx' but not 'xxx.aa')
  18634. * });
  18635. * eachComponent(
  18636. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  18637. * function (model, index) {...}
  18638. * );
  18639. * eachComponent(
  18640. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  18641. * function (model, index) {...}
  18642. * );
  18643. *
  18644. * @param {string|Object=} mainType When mainType is object, the definition
  18645. * is the same as the method 'findComponents'.
  18646. * @param {Function} cb
  18647. * @param {*} context
  18648. */
  18649. eachComponent: function (mainType, cb, context) {
  18650. var componentsMap = this._componentsMap;
  18651. if (typeof mainType === 'function') {
  18652. context = cb;
  18653. cb = mainType;
  18654. componentsMap.each(function (components, componentType) {
  18655. each$1(components, function (component, index) {
  18656. cb.call(context, componentType, component, index);
  18657. });
  18658. });
  18659. }
  18660. else if (isString(mainType)) {
  18661. each$1(componentsMap.get(mainType), cb, context);
  18662. }
  18663. else if (isObject$1(mainType)) {
  18664. var queryResult = this.findComponents(mainType);
  18665. each$1(queryResult, cb, context);
  18666. }
  18667. },
  18668. /**
  18669. * @param {string} name
  18670. * @return {Array.<module:echarts/model/Series>}
  18671. */
  18672. getSeriesByName: function (name) {
  18673. var series = this._componentsMap.get('series');
  18674. return filter(series, function (oneSeries) {
  18675. return oneSeries.name === name;
  18676. });
  18677. },
  18678. /**
  18679. * @param {number} seriesIndex
  18680. * @return {module:echarts/model/Series}
  18681. */
  18682. getSeriesByIndex: function (seriesIndex) {
  18683. return this._componentsMap.get('series')[seriesIndex];
  18684. },
  18685. /**
  18686. * Get series list before filtered by type.
  18687. * FIXME: rename to getRawSeriesByType?
  18688. *
  18689. * @param {string} subType
  18690. * @return {Array.<module:echarts/model/Series>}
  18691. */
  18692. getSeriesByType: function (subType) {
  18693. var series = this._componentsMap.get('series');
  18694. return filter(series, function (oneSeries) {
  18695. return oneSeries.subType === subType;
  18696. });
  18697. },
  18698. /**
  18699. * @return {Array.<module:echarts/model/Series>}
  18700. */
  18701. getSeries: function () {
  18702. return this._componentsMap.get('series').slice();
  18703. },
  18704. /**
  18705. * @return {number}
  18706. */
  18707. getSeriesCount: function () {
  18708. return this._componentsMap.get('series').length;
  18709. },
  18710. /**
  18711. * After filtering, series may be different
  18712. * frome raw series.
  18713. *
  18714. * @param {Function} cb
  18715. * @param {*} context
  18716. */
  18717. eachSeries: function (cb, context) {
  18718. assertSeriesInitialized(this);
  18719. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18720. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18721. cb.call(context, series, rawSeriesIndex);
  18722. }, this);
  18723. },
  18724. /**
  18725. * Iterate raw series before filtered.
  18726. *
  18727. * @param {Function} cb
  18728. * @param {*} context
  18729. */
  18730. eachRawSeries: function (cb, context) {
  18731. each$1(this._componentsMap.get('series'), cb, context);
  18732. },
  18733. /**
  18734. * After filtering, series may be different.
  18735. * frome raw series.
  18736. *
  18737. * @parma {string} subType
  18738. * @param {Function} cb
  18739. * @param {*} context
  18740. */
  18741. eachSeriesByType: function (subType, cb, context) {
  18742. assertSeriesInitialized(this);
  18743. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18744. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18745. if (series.subType === subType) {
  18746. cb.call(context, series, rawSeriesIndex);
  18747. }
  18748. }, this);
  18749. },
  18750. /**
  18751. * Iterate raw series before filtered of given type.
  18752. *
  18753. * @parma {string} subType
  18754. * @param {Function} cb
  18755. * @param {*} context
  18756. */
  18757. eachRawSeriesByType: function (subType, cb, context) {
  18758. return each$1(this.getSeriesByType(subType), cb, context);
  18759. },
  18760. /**
  18761. * @param {module:echarts/model/Series} seriesModel
  18762. */
  18763. isSeriesFiltered: function (seriesModel) {
  18764. assertSeriesInitialized(this);
  18765. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  18766. },
  18767. /**
  18768. * @return {Array.<number>}
  18769. */
  18770. getCurrentSeriesIndices: function () {
  18771. return (this._seriesIndices || []).slice();
  18772. },
  18773. /**
  18774. * @param {Function} cb
  18775. * @param {*} context
  18776. */
  18777. filterSeries: function (cb, context) {
  18778. assertSeriesInitialized(this);
  18779. var filteredSeries = filter(
  18780. this._componentsMap.get('series'), cb, context
  18781. );
  18782. createSeriesIndices(this, filteredSeries);
  18783. },
  18784. restoreData: function (payload) {
  18785. var componentsMap = this._componentsMap;
  18786. createSeriesIndices(this, componentsMap.get('series'));
  18787. var componentTypes = [];
  18788. componentsMap.each(function (components, componentType) {
  18789. componentTypes.push(componentType);
  18790. });
  18791. ComponentModel.topologicalTravel(
  18792. componentTypes,
  18793. ComponentModel.getAllClassMainTypes(),
  18794. function (componentType, dependencies) {
  18795. each$1(componentsMap.get(componentType), function (component) {
  18796. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  18797. && component.restoreData();
  18798. });
  18799. }
  18800. );
  18801. }
  18802. });
  18803. function isNotTargetSeries(seriesModel, payload) {
  18804. if (payload) {
  18805. var index = payload.seiresIndex;
  18806. var id = payload.seriesId;
  18807. var name = payload.seriesName;
  18808. return (index != null && seriesModel.componentIndex !== index)
  18809. || (id != null && seriesModel.id !== id)
  18810. || (name != null && seriesModel.name !== name);
  18811. }
  18812. }
  18813. /**
  18814. * @inner
  18815. */
  18816. function mergeTheme(option, theme) {
  18817. // PENDING
  18818. // NOT use `colorLayer` in theme if option has `color`
  18819. var notMergeColorLayer = option.color && !option.colorLayer;
  18820. each$1(theme, function (themeItem, name) {
  18821. if (name === 'colorLayer' && notMergeColorLayer) {
  18822. return;
  18823. }
  18824. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  18825. if (!ComponentModel.hasClass(name)) {
  18826. if (typeof themeItem === 'object') {
  18827. option[name] = !option[name]
  18828. ? clone(themeItem)
  18829. : merge(option[name], themeItem, false);
  18830. }
  18831. else {
  18832. if (option[name] == null) {
  18833. option[name] = themeItem;
  18834. }
  18835. }
  18836. }
  18837. });
  18838. }
  18839. function initBase(baseOption) {
  18840. baseOption = baseOption;
  18841. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  18842. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  18843. this.option = {};
  18844. this.option[OPTION_INNER_KEY] = 1;
  18845. /**
  18846. * Init with series: [], in case of calling findSeries method
  18847. * before series initialized.
  18848. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18849. * @private
  18850. */
  18851. this._componentsMap = createHashMap({series: []});
  18852. /**
  18853. * Mapping between filtered series list and raw series list.
  18854. * key: filtered series indices, value: raw series indices.
  18855. * @type {Array.<nubmer>}
  18856. * @private
  18857. */
  18858. this._seriesIndices;
  18859. this._seriesIndicesMap;
  18860. mergeTheme(baseOption, this._theme.option);
  18861. // TODO Needs clone when merging to the unexisted property
  18862. merge(baseOption, globalDefault, false);
  18863. this.mergeOption(baseOption);
  18864. }
  18865. /**
  18866. * @inner
  18867. * @param {Array.<string>|string} types model types
  18868. * @return {Object} key: {string} type, value: {Array.<Object>} models
  18869. */
  18870. function getComponentsByTypes(componentsMap, types) {
  18871. if (!isArray(types)) {
  18872. types = types ? [types] : [];
  18873. }
  18874. var ret = {};
  18875. each$1(types, function (type) {
  18876. ret[type] = (componentsMap.get(type) || []).slice();
  18877. });
  18878. return ret;
  18879. }
  18880. /**
  18881. * @inner
  18882. */
  18883. function determineSubType(mainType, newCptOption, existComponent) {
  18884. var subType = newCptOption.type
  18885. ? newCptOption.type
  18886. : existComponent
  18887. ? existComponent.subType
  18888. // Use determineSubType only when there is no existComponent.
  18889. : ComponentModel.determineSubType(mainType, newCptOption);
  18890. // tooltip, markline, markpoint may always has no subType
  18891. return subType;
  18892. }
  18893. /**
  18894. * @inner
  18895. */
  18896. function createSeriesIndices(ecModel, seriesModels) {
  18897. ecModel._seriesIndicesMap = createHashMap(
  18898. ecModel._seriesIndices = map(seriesModels, function (series) {
  18899. return series.componentIndex;
  18900. }) || []
  18901. );
  18902. }
  18903. /**
  18904. * @inner
  18905. */
  18906. function filterBySubType(components, condition) {
  18907. // Using hasOwnProperty for restrict. Consider
  18908. // subType is undefined in user payload.
  18909. return condition.hasOwnProperty('subType')
  18910. ? filter(components, function (cpt) {
  18911. return cpt.subType === condition.subType;
  18912. })
  18913. : components;
  18914. }
  18915. /**
  18916. * @inner
  18917. */
  18918. function assertSeriesInitialized(ecModel) {
  18919. // Components that use _seriesIndices should depends on series component,
  18920. // which make sure that their initialization is after series.
  18921. if (__DEV__) {
  18922. if (!ecModel._seriesIndices) {
  18923. throw new Error('Option should contains series.');
  18924. }
  18925. }
  18926. }
  18927. mixin(GlobalModel, colorPaletteMixin);
  18928. /*
  18929. * Licensed to the Apache Software Foundation (ASF) under one
  18930. * or more contributor license agreements. See the NOTICE file
  18931. * distributed with this work for additional information
  18932. * regarding copyright ownership. The ASF licenses this file
  18933. * to you under the Apache License, Version 2.0 (the
  18934. * "License"); you may not use this file except in compliance
  18935. * with the License. You may obtain a copy of the License at
  18936. *
  18937. * http://www.apache.org/licenses/LICENSE-2.0
  18938. *
  18939. * Unless required by applicable law or agreed to in writing,
  18940. * software distributed under the License is distributed on an
  18941. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18942. * KIND, either express or implied. See the License for the
  18943. * specific language governing permissions and limitations
  18944. * under the License.
  18945. */
  18946. var echartsAPIList = [
  18947. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  18948. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  18949. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  18950. ];
  18951. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  18952. function ExtensionAPI(chartInstance) {
  18953. each$1(echartsAPIList, function (name) {
  18954. this[name] = bind(chartInstance[name], chartInstance);
  18955. }, this);
  18956. }
  18957. /*
  18958. * Licensed to the Apache Software Foundation (ASF) under one
  18959. * or more contributor license agreements. See the NOTICE file
  18960. * distributed with this work for additional information
  18961. * regarding copyright ownership. The ASF licenses this file
  18962. * to you under the Apache License, Version 2.0 (the
  18963. * "License"); you may not use this file except in compliance
  18964. * with the License. You may obtain a copy of the License at
  18965. *
  18966. * http://www.apache.org/licenses/LICENSE-2.0
  18967. *
  18968. * Unless required by applicable law or agreed to in writing,
  18969. * software distributed under the License is distributed on an
  18970. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18971. * KIND, either express or implied. See the License for the
  18972. * specific language governing permissions and limitations
  18973. * under the License.
  18974. */
  18975. var coordinateSystemCreators = {};
  18976. function CoordinateSystemManager() {
  18977. this._coordinateSystems = [];
  18978. }
  18979. CoordinateSystemManager.prototype = {
  18980. constructor: CoordinateSystemManager,
  18981. create: function (ecModel, api) {
  18982. var coordinateSystems = [];
  18983. each$1(coordinateSystemCreators, function (creater, type) {
  18984. var list = creater.create(ecModel, api);
  18985. coordinateSystems = coordinateSystems.concat(list || []);
  18986. });
  18987. this._coordinateSystems = coordinateSystems;
  18988. },
  18989. update: function (ecModel, api) {
  18990. each$1(this._coordinateSystems, function (coordSys) {
  18991. coordSys.update && coordSys.update(ecModel, api);
  18992. });
  18993. },
  18994. getCoordinateSystems: function () {
  18995. return this._coordinateSystems.slice();
  18996. }
  18997. };
  18998. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  18999. coordinateSystemCreators[type] = coordinateSystemCreator;
  19000. };
  19001. CoordinateSystemManager.get = function (type) {
  19002. return coordinateSystemCreators[type];
  19003. };
  19004. /*
  19005. * Licensed to the Apache Software Foundation (ASF) under one
  19006. * or more contributor license agreements. See the NOTICE file
  19007. * distributed with this work for additional information
  19008. * regarding copyright ownership. The ASF licenses this file
  19009. * to you under the Apache License, Version 2.0 (the
  19010. * "License"); you may not use this file except in compliance
  19011. * with the License. You may obtain a copy of the License at
  19012. *
  19013. * http://www.apache.org/licenses/LICENSE-2.0
  19014. *
  19015. * Unless required by applicable law or agreed to in writing,
  19016. * software distributed under the License is distributed on an
  19017. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19018. * KIND, either express or implied. See the License for the
  19019. * specific language governing permissions and limitations
  19020. * under the License.
  19021. */
  19022. /**
  19023. * ECharts option manager
  19024. *
  19025. * @module {echarts/model/OptionManager}
  19026. */
  19027. var each$4 = each$1;
  19028. var clone$3 = clone;
  19029. var map$1 = map;
  19030. var merge$1 = merge;
  19031. var QUERY_REG = /^(min|max)?(.+)$/;
  19032. /**
  19033. * TERM EXPLANATIONS:
  19034. *
  19035. * [option]:
  19036. *
  19037. * An object that contains definitions of components. For example:
  19038. * var option = {
  19039. * title: {...},
  19040. * legend: {...},
  19041. * visualMap: {...},
  19042. * series: [
  19043. * {data: [...]},
  19044. * {data: [...]},
  19045. * ...
  19046. * ]
  19047. * };
  19048. *
  19049. * [rawOption]:
  19050. *
  19051. * An object input to echarts.setOption. 'rawOption' may be an
  19052. * 'option', or may be an object contains multi-options. For example:
  19053. * var option = {
  19054. * baseOption: {
  19055. * title: {...},
  19056. * legend: {...},
  19057. * series: [
  19058. * {data: [...]},
  19059. * {data: [...]},
  19060. * ...
  19061. * ]
  19062. * },
  19063. * timeline: {...},
  19064. * options: [
  19065. * {title: {...}, series: {data: [...]}},
  19066. * {title: {...}, series: {data: [...]}},
  19067. * ...
  19068. * ],
  19069. * media: [
  19070. * {
  19071. * query: {maxWidth: 320},
  19072. * option: {series: {x: 20}, visualMap: {show: false}}
  19073. * },
  19074. * {
  19075. * query: {minWidth: 320, maxWidth: 720},
  19076. * option: {series: {x: 500}, visualMap: {show: true}}
  19077. * },
  19078. * {
  19079. * option: {series: {x: 1200}, visualMap: {show: true}}
  19080. * }
  19081. * ]
  19082. * };
  19083. *
  19084. * @alias module:echarts/model/OptionManager
  19085. * @param {module:echarts/ExtensionAPI} api
  19086. */
  19087. function OptionManager(api) {
  19088. /**
  19089. * @private
  19090. * @type {module:echarts/ExtensionAPI}
  19091. */
  19092. this._api = api;
  19093. /**
  19094. * @private
  19095. * @type {Array.<number>}
  19096. */
  19097. this._timelineOptions = [];
  19098. /**
  19099. * @private
  19100. * @type {Array.<Object>}
  19101. */
  19102. this._mediaList = [];
  19103. /**
  19104. * @private
  19105. * @type {Object}
  19106. */
  19107. this._mediaDefault;
  19108. /**
  19109. * -1, means default.
  19110. * empty means no media.
  19111. * @private
  19112. * @type {Array.<number>}
  19113. */
  19114. this._currentMediaIndices = [];
  19115. /**
  19116. * @private
  19117. * @type {Object}
  19118. */
  19119. this._optionBackup;
  19120. /**
  19121. * @private
  19122. * @type {Object}
  19123. */
  19124. this._newBaseOption;
  19125. }
  19126. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19127. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19128. // rawOption cloned and backuped when timeline changed, which does no
  19129. // good to performance. What's more, that both timeline and setOption
  19130. // method supply 'notMerge' brings complex and some problems.
  19131. // Consider this case:
  19132. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19133. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19134. OptionManager.prototype = {
  19135. constructor: OptionManager,
  19136. /**
  19137. * @public
  19138. * @param {Object} rawOption Raw option.
  19139. * @param {module:echarts/model/Global} ecModel
  19140. * @param {Array.<Function>} optionPreprocessorFuncs
  19141. * @return {Object} Init option
  19142. */
  19143. setOption: function (rawOption, optionPreprocessorFuncs) {
  19144. if (rawOption) {
  19145. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19146. each$1(normalizeToArray(rawOption.series), function (series) {
  19147. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19148. });
  19149. }
  19150. // Caution: some series modify option data, if do not clone,
  19151. // it should ensure that the repeat modify correctly
  19152. // (create a new object when modify itself).
  19153. rawOption = clone$3(rawOption, true);
  19154. // FIXME
  19155. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  19156. var oldOptionBackup = this._optionBackup;
  19157. var newParsedOption = parseRawOption.call(
  19158. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  19159. );
  19160. this._newBaseOption = newParsedOption.baseOption;
  19161. // For setOption at second time (using merge mode);
  19162. if (oldOptionBackup) {
  19163. // Only baseOption can be merged.
  19164. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  19165. // For simplicity, timeline options and media options do not support merge,
  19166. // that is, if you `setOption` twice and both has timeline options, the latter
  19167. // timeline opitons will not be merged to the formers, but just substitude them.
  19168. if (newParsedOption.timelineOptions.length) {
  19169. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  19170. }
  19171. if (newParsedOption.mediaList.length) {
  19172. oldOptionBackup.mediaList = newParsedOption.mediaList;
  19173. }
  19174. if (newParsedOption.mediaDefault) {
  19175. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  19176. }
  19177. }
  19178. else {
  19179. this._optionBackup = newParsedOption;
  19180. }
  19181. },
  19182. /**
  19183. * @param {boolean} isRecreate
  19184. * @return {Object}
  19185. */
  19186. mountOption: function (isRecreate) {
  19187. var optionBackup = this._optionBackup;
  19188. // TODO
  19189. // 如果没有reset功能则不clone。
  19190. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  19191. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  19192. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  19193. this._currentMediaIndices = [];
  19194. return clone$3(isRecreate
  19195. // this._optionBackup.baseOption, which is created at the first `setOption`
  19196. // called, and is merged into every new option by inner method `mergeOption`
  19197. // each time `setOption` called, can be only used in `isRecreate`, because
  19198. // its reliability is under suspicion. In other cases option merge is
  19199. // performed by `model.mergeOption`.
  19200. ? optionBackup.baseOption : this._newBaseOption
  19201. );
  19202. },
  19203. /**
  19204. * @param {module:echarts/model/Global} ecModel
  19205. * @return {Object}
  19206. */
  19207. getTimelineOption: function (ecModel) {
  19208. var option;
  19209. var timelineOptions = this._timelineOptions;
  19210. if (timelineOptions.length) {
  19211. // getTimelineOption can only be called after ecModel inited,
  19212. // so we can get currentIndex from timelineModel.
  19213. var timelineModel = ecModel.getComponent('timeline');
  19214. if (timelineModel) {
  19215. option = clone$3(
  19216. timelineOptions[timelineModel.getCurrentIndex()],
  19217. true
  19218. );
  19219. }
  19220. }
  19221. return option;
  19222. },
  19223. /**
  19224. * @param {module:echarts/model/Global} ecModel
  19225. * @return {Array.<Object>}
  19226. */
  19227. getMediaOption: function (ecModel) {
  19228. var ecWidth = this._api.getWidth();
  19229. var ecHeight = this._api.getHeight();
  19230. var mediaList = this._mediaList;
  19231. var mediaDefault = this._mediaDefault;
  19232. var indices = [];
  19233. var result = [];
  19234. // No media defined.
  19235. if (!mediaList.length && !mediaDefault) {
  19236. return result;
  19237. }
  19238. // Multi media may be applied, the latter defined media has higher priority.
  19239. for (var i = 0, len = mediaList.length; i < len; i++) {
  19240. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  19241. indices.push(i);
  19242. }
  19243. }
  19244. // FIXME
  19245. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  19246. if (!indices.length && mediaDefault) {
  19247. indices = [-1];
  19248. }
  19249. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  19250. result = map$1(indices, function (index) {
  19251. return clone$3(
  19252. index === -1 ? mediaDefault.option : mediaList[index].option
  19253. );
  19254. });
  19255. }
  19256. // Otherwise return nothing.
  19257. this._currentMediaIndices = indices;
  19258. return result;
  19259. }
  19260. };
  19261. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  19262. var timelineOptions = [];
  19263. var mediaList = [];
  19264. var mediaDefault;
  19265. var baseOption;
  19266. // Compatible with ec2.
  19267. var timelineOpt = rawOption.timeline;
  19268. if (rawOption.baseOption) {
  19269. baseOption = rawOption.baseOption;
  19270. }
  19271. // For timeline
  19272. if (timelineOpt || rawOption.options) {
  19273. baseOption = baseOption || {};
  19274. timelineOptions = (rawOption.options || []).slice();
  19275. }
  19276. // For media query
  19277. if (rawOption.media) {
  19278. baseOption = baseOption || {};
  19279. var media = rawOption.media;
  19280. each$4(media, function (singleMedia) {
  19281. if (singleMedia && singleMedia.option) {
  19282. if (singleMedia.query) {
  19283. mediaList.push(singleMedia);
  19284. }
  19285. else if (!mediaDefault) {
  19286. // Use the first media default.
  19287. mediaDefault = singleMedia;
  19288. }
  19289. }
  19290. });
  19291. }
  19292. // For normal option
  19293. if (!baseOption) {
  19294. baseOption = rawOption;
  19295. }
  19296. // Set timelineOpt to baseOption in ec3,
  19297. // which is convenient for merge option.
  19298. if (!baseOption.timeline) {
  19299. baseOption.timeline = timelineOpt;
  19300. }
  19301. // Preprocess.
  19302. each$4([baseOption].concat(timelineOptions)
  19303. .concat(map(mediaList, function (media) {
  19304. return media.option;
  19305. })),
  19306. function (option) {
  19307. each$4(optionPreprocessorFuncs, function (preProcess) {
  19308. preProcess(option, isNew);
  19309. });
  19310. }
  19311. );
  19312. return {
  19313. baseOption: baseOption,
  19314. timelineOptions: timelineOptions,
  19315. mediaDefault: mediaDefault,
  19316. mediaList: mediaList
  19317. };
  19318. }
  19319. /**
  19320. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  19321. * Support: width, height, aspectRatio
  19322. * Can use max or min as prefix.
  19323. */
  19324. function applyMediaQuery(query, ecWidth, ecHeight) {
  19325. var realMap = {
  19326. width: ecWidth,
  19327. height: ecHeight,
  19328. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  19329. };
  19330. var applicatable = true;
  19331. each$1(query, function (value, attr) {
  19332. var matched = attr.match(QUERY_REG);
  19333. if (!matched || !matched[1] || !matched[2]) {
  19334. return;
  19335. }
  19336. var operator = matched[1];
  19337. var realAttr = matched[2].toLowerCase();
  19338. if (!compare(realMap[realAttr], value, operator)) {
  19339. applicatable = false;
  19340. }
  19341. });
  19342. return applicatable;
  19343. }
  19344. function compare(real, expect, operator) {
  19345. if (operator === 'min') {
  19346. return real >= expect;
  19347. }
  19348. else if (operator === 'max') {
  19349. return real <= expect;
  19350. }
  19351. else { // Equals
  19352. return real === expect;
  19353. }
  19354. }
  19355. function indicesEquals(indices1, indices2) {
  19356. // indices is always order by asc and has only finite number.
  19357. return indices1.join(',') === indices2.join(',');
  19358. }
  19359. /**
  19360. * Consider case:
  19361. * `chart.setOption(opt1);`
  19362. * Then user do some interaction like dataZoom, dataView changing.
  19363. * `chart.setOption(opt2);`
  19364. * Then user press 'reset button' in toolbox.
  19365. *
  19366. * After doing that all of the interaction effects should be reset, the
  19367. * chart should be the same as the result of invoke
  19368. * `chart.setOption(opt1); chart.setOption(opt2);`.
  19369. *
  19370. * Although it is not able ensure that
  19371. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  19372. * `chart.setOption(merge(opt1, opt2));` exactly,
  19373. * this might be the only simple way to implement that feature.
  19374. *
  19375. * MEMO: We've considered some other approaches:
  19376. * 1. Each model handle its self restoration but not uniform treatment.
  19377. * (Too complex in logic and error-prone)
  19378. * 2. Use a shadow ecModel. (Performace expensive)
  19379. */
  19380. function mergeOption(oldOption, newOption) {
  19381. newOption = newOption || {};
  19382. each$4(newOption, function (newCptOpt, mainType) {
  19383. if (newCptOpt == null) {
  19384. return;
  19385. }
  19386. var oldCptOpt = oldOption[mainType];
  19387. if (!ComponentModel.hasClass(mainType)) {
  19388. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  19389. }
  19390. else {
  19391. newCptOpt = normalizeToArray(newCptOpt);
  19392. oldCptOpt = normalizeToArray(oldCptOpt);
  19393. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  19394. oldOption[mainType] = map$1(mapResult, function (item) {
  19395. return (item.option && item.exist)
  19396. ? merge$1(item.exist, item.option, true)
  19397. : (item.exist || item.option);
  19398. });
  19399. }
  19400. });
  19401. }
  19402. /*
  19403. * Licensed to the Apache Software Foundation (ASF) under one
  19404. * or more contributor license agreements. See the NOTICE file
  19405. * distributed with this work for additional information
  19406. * regarding copyright ownership. The ASF licenses this file
  19407. * to you under the Apache License, Version 2.0 (the
  19408. * "License"); you may not use this file except in compliance
  19409. * with the License. You may obtain a copy of the License at
  19410. *
  19411. * http://www.apache.org/licenses/LICENSE-2.0
  19412. *
  19413. * Unless required by applicable law or agreed to in writing,
  19414. * software distributed under the License is distributed on an
  19415. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19416. * KIND, either express or implied. See the License for the
  19417. * specific language governing permissions and limitations
  19418. * under the License.
  19419. */
  19420. var each$5 = each$1;
  19421. var isObject$3 = isObject$1;
  19422. var POSSIBLE_STYLES = [
  19423. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  19424. 'chordStyle', 'label', 'labelLine'
  19425. ];
  19426. function compatEC2ItemStyle(opt) {
  19427. var itemStyleOpt = opt && opt.itemStyle;
  19428. if (!itemStyleOpt) {
  19429. return;
  19430. }
  19431. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  19432. var styleName = POSSIBLE_STYLES[i];
  19433. var normalItemStyleOpt = itemStyleOpt.normal;
  19434. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  19435. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  19436. opt[styleName] = opt[styleName] || {};
  19437. if (!opt[styleName].normal) {
  19438. opt[styleName].normal = normalItemStyleOpt[styleName];
  19439. }
  19440. else {
  19441. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  19442. }
  19443. normalItemStyleOpt[styleName] = null;
  19444. }
  19445. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  19446. opt[styleName] = opt[styleName] || {};
  19447. if (!opt[styleName].emphasis) {
  19448. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  19449. }
  19450. else {
  19451. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  19452. }
  19453. emphasisItemStyleOpt[styleName] = null;
  19454. }
  19455. }
  19456. }
  19457. function convertNormalEmphasis(opt, optType, useExtend) {
  19458. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  19459. var normalOpt = opt[optType].normal;
  19460. var emphasisOpt = opt[optType].emphasis;
  19461. if (normalOpt) {
  19462. // Timeline controlStyle has other properties besides normal and emphasis
  19463. if (useExtend) {
  19464. opt[optType].normal = opt[optType].emphasis = null;
  19465. defaults(opt[optType], normalOpt);
  19466. }
  19467. else {
  19468. opt[optType] = normalOpt;
  19469. }
  19470. }
  19471. if (emphasisOpt) {
  19472. opt.emphasis = opt.emphasis || {};
  19473. opt.emphasis[optType] = emphasisOpt;
  19474. }
  19475. }
  19476. }
  19477. function removeEC3NormalStatus(opt) {
  19478. convertNormalEmphasis(opt, 'itemStyle');
  19479. convertNormalEmphasis(opt, 'lineStyle');
  19480. convertNormalEmphasis(opt, 'areaStyle');
  19481. convertNormalEmphasis(opt, 'label');
  19482. convertNormalEmphasis(opt, 'labelLine');
  19483. // treemap
  19484. convertNormalEmphasis(opt, 'upperLabel');
  19485. // graph
  19486. convertNormalEmphasis(opt, 'edgeLabel');
  19487. }
  19488. function compatTextStyle(opt, propName) {
  19489. // Check whether is not object (string\null\undefined ...)
  19490. var labelOptSingle = isObject$3(opt) && opt[propName];
  19491. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  19492. if (textStyle) {
  19493. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  19494. var propName = TEXT_STYLE_OPTIONS[i];
  19495. if (textStyle.hasOwnProperty(propName)) {
  19496. labelOptSingle[propName] = textStyle[propName];
  19497. }
  19498. }
  19499. }
  19500. }
  19501. function compatEC3CommonStyles(opt) {
  19502. if (opt) {
  19503. removeEC3NormalStatus(opt);
  19504. compatTextStyle(opt, 'label');
  19505. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  19506. }
  19507. }
  19508. function processSeries(seriesOpt) {
  19509. if (!isObject$3(seriesOpt)) {
  19510. return;
  19511. }
  19512. compatEC2ItemStyle(seriesOpt);
  19513. removeEC3NormalStatus(seriesOpt);
  19514. compatTextStyle(seriesOpt, 'label');
  19515. // treemap
  19516. compatTextStyle(seriesOpt, 'upperLabel');
  19517. // graph
  19518. compatTextStyle(seriesOpt, 'edgeLabel');
  19519. if (seriesOpt.emphasis) {
  19520. compatTextStyle(seriesOpt.emphasis, 'label');
  19521. // treemap
  19522. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  19523. // graph
  19524. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  19525. }
  19526. var markPoint = seriesOpt.markPoint;
  19527. if (markPoint) {
  19528. compatEC2ItemStyle(markPoint);
  19529. compatEC3CommonStyles(markPoint);
  19530. }
  19531. var markLine = seriesOpt.markLine;
  19532. if (markLine) {
  19533. compatEC2ItemStyle(markLine);
  19534. compatEC3CommonStyles(markLine);
  19535. }
  19536. var markArea = seriesOpt.markArea;
  19537. if (markArea) {
  19538. compatEC3CommonStyles(markArea);
  19539. }
  19540. var data = seriesOpt.data;
  19541. // Break with ec3: if `setOption` again, there may be no `type` in option,
  19542. // then the backward compat based on option type will not be performed.
  19543. if (seriesOpt.type === 'graph') {
  19544. data = data || seriesOpt.nodes;
  19545. var edgeData = seriesOpt.links || seriesOpt.edges;
  19546. if (edgeData && !isTypedArray(edgeData)) {
  19547. for (var i = 0; i < edgeData.length; i++) {
  19548. compatEC3CommonStyles(edgeData[i]);
  19549. }
  19550. }
  19551. each$1(seriesOpt.categories, function (opt) {
  19552. removeEC3NormalStatus(opt);
  19553. });
  19554. }
  19555. if (data && !isTypedArray(data)) {
  19556. for (var i = 0; i < data.length; i++) {
  19557. compatEC3CommonStyles(data[i]);
  19558. }
  19559. }
  19560. // mark point data
  19561. var markPoint = seriesOpt.markPoint;
  19562. if (markPoint && markPoint.data) {
  19563. var mpData = markPoint.data;
  19564. for (var i = 0; i < mpData.length; i++) {
  19565. compatEC3CommonStyles(mpData[i]);
  19566. }
  19567. }
  19568. // mark line data
  19569. var markLine = seriesOpt.markLine;
  19570. if (markLine && markLine.data) {
  19571. var mlData = markLine.data;
  19572. for (var i = 0; i < mlData.length; i++) {
  19573. if (isArray(mlData[i])) {
  19574. compatEC3CommonStyles(mlData[i][0]);
  19575. compatEC3CommonStyles(mlData[i][1]);
  19576. }
  19577. else {
  19578. compatEC3CommonStyles(mlData[i]);
  19579. }
  19580. }
  19581. }
  19582. // Series
  19583. if (seriesOpt.type === 'gauge') {
  19584. compatTextStyle(seriesOpt, 'axisLabel');
  19585. compatTextStyle(seriesOpt, 'title');
  19586. compatTextStyle(seriesOpt, 'detail');
  19587. }
  19588. else if (seriesOpt.type === 'treemap') {
  19589. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  19590. each$1(seriesOpt.levels, function (opt) {
  19591. removeEC3NormalStatus(opt);
  19592. });
  19593. }
  19594. else if (seriesOpt.type === 'tree') {
  19595. removeEC3NormalStatus(seriesOpt.leaves);
  19596. }
  19597. // sunburst starts from ec4, so it does not need to compat levels.
  19598. }
  19599. function toArr(o) {
  19600. return isArray(o) ? o : o ? [o] : [];
  19601. }
  19602. function toObj(o) {
  19603. return (isArray(o) ? o[0] : o) || {};
  19604. }
  19605. var compatStyle = function (option, isTheme) {
  19606. each$5(toArr(option.series), function (seriesOpt) {
  19607. isObject$3(seriesOpt) && processSeries(seriesOpt);
  19608. });
  19609. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  19610. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  19611. each$5(
  19612. axes,
  19613. function (axisName) {
  19614. each$5(toArr(option[axisName]), function (axisOpt) {
  19615. if (axisOpt) {
  19616. compatTextStyle(axisOpt, 'axisLabel');
  19617. compatTextStyle(axisOpt.axisPointer, 'label');
  19618. }
  19619. });
  19620. }
  19621. );
  19622. each$5(toArr(option.parallel), function (parallelOpt) {
  19623. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  19624. compatTextStyle(parallelAxisDefault, 'axisLabel');
  19625. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  19626. });
  19627. each$5(toArr(option.calendar), function (calendarOpt) {
  19628. convertNormalEmphasis(calendarOpt, 'itemStyle');
  19629. compatTextStyle(calendarOpt, 'dayLabel');
  19630. compatTextStyle(calendarOpt, 'monthLabel');
  19631. compatTextStyle(calendarOpt, 'yearLabel');
  19632. });
  19633. // radar.name.textStyle
  19634. each$5(toArr(option.radar), function (radarOpt) {
  19635. compatTextStyle(radarOpt, 'name');
  19636. });
  19637. each$5(toArr(option.geo), function (geoOpt) {
  19638. if (isObject$3(geoOpt)) {
  19639. compatEC3CommonStyles(geoOpt);
  19640. each$5(toArr(geoOpt.regions), function (regionObj) {
  19641. compatEC3CommonStyles(regionObj);
  19642. });
  19643. }
  19644. });
  19645. each$5(toArr(option.timeline), function (timelineOpt) {
  19646. compatEC3CommonStyles(timelineOpt);
  19647. convertNormalEmphasis(timelineOpt, 'label');
  19648. convertNormalEmphasis(timelineOpt, 'itemStyle');
  19649. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  19650. var data = timelineOpt.data;
  19651. isArray(data) && each$1(data, function (item) {
  19652. if (isObject$1(item)) {
  19653. convertNormalEmphasis(item, 'label');
  19654. convertNormalEmphasis(item, 'itemStyle');
  19655. }
  19656. });
  19657. });
  19658. each$5(toArr(option.toolbox), function (toolboxOpt) {
  19659. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  19660. each$5(toolboxOpt.feature, function (featureOpt) {
  19661. convertNormalEmphasis(featureOpt, 'iconStyle');
  19662. });
  19663. });
  19664. compatTextStyle(toObj(option.axisPointer), 'label');
  19665. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  19666. };
  19667. /*
  19668. * Licensed to the Apache Software Foundation (ASF) under one
  19669. * or more contributor license agreements. See the NOTICE file
  19670. * distributed with this work for additional information
  19671. * regarding copyright ownership. The ASF licenses this file
  19672. * to you under the Apache License, Version 2.0 (the
  19673. * "License"); you may not use this file except in compliance
  19674. * with the License. You may obtain a copy of the License at
  19675. *
  19676. * http://www.apache.org/licenses/LICENSE-2.0
  19677. *
  19678. * Unless required by applicable law or agreed to in writing,
  19679. * software distributed under the License is distributed on an
  19680. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19681. * KIND, either express or implied. See the License for the
  19682. * specific language governing permissions and limitations
  19683. * under the License.
  19684. */
  19685. // Compatitable with 2.0
  19686. function get(opt, path) {
  19687. path = path.split(',');
  19688. var obj = opt;
  19689. for (var i = 0; i < path.length; i++) {
  19690. obj = obj && obj[path[i]];
  19691. if (obj == null) {
  19692. break;
  19693. }
  19694. }
  19695. return obj;
  19696. }
  19697. function set$1(opt, path, val, overwrite) {
  19698. path = path.split(',');
  19699. var obj = opt;
  19700. var key;
  19701. for (var i = 0; i < path.length - 1; i++) {
  19702. key = path[i];
  19703. if (obj[key] == null) {
  19704. obj[key] = {};
  19705. }
  19706. obj = obj[key];
  19707. }
  19708. if (overwrite || obj[path[i]] == null) {
  19709. obj[path[i]] = val;
  19710. }
  19711. }
  19712. function compatLayoutProperties(option) {
  19713. each$1(LAYOUT_PROPERTIES, function (prop) {
  19714. if (prop[0] in option && !(prop[1] in option)) {
  19715. option[prop[1]] = option[prop[0]];
  19716. }
  19717. });
  19718. }
  19719. var LAYOUT_PROPERTIES = [
  19720. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  19721. ];
  19722. var COMPATITABLE_COMPONENTS = [
  19723. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  19724. ];
  19725. var backwardCompat = function (option, isTheme) {
  19726. compatStyle(option, isTheme);
  19727. // Make sure series array for model initialization.
  19728. option.series = normalizeToArray(option.series);
  19729. each$1(option.series, function (seriesOpt) {
  19730. if (!isObject$1(seriesOpt)) {
  19731. return;
  19732. }
  19733. var seriesType = seriesOpt.type;
  19734. if (seriesType === 'pie' || seriesType === 'gauge') {
  19735. if (seriesOpt.clockWise != null) {
  19736. seriesOpt.clockwise = seriesOpt.clockWise;
  19737. }
  19738. }
  19739. if (seriesType === 'gauge') {
  19740. var pointerColor = get(seriesOpt, 'pointer.color');
  19741. pointerColor != null
  19742. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  19743. }
  19744. compatLayoutProperties(seriesOpt);
  19745. });
  19746. // dataRange has changed to visualMap
  19747. if (option.dataRange) {
  19748. option.visualMap = option.dataRange;
  19749. }
  19750. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  19751. var options = option[componentName];
  19752. if (options) {
  19753. if (!isArray(options)) {
  19754. options = [options];
  19755. }
  19756. each$1(options, function (option) {
  19757. compatLayoutProperties(option);
  19758. });
  19759. }
  19760. });
  19761. };
  19762. /*
  19763. * Licensed to the Apache Software Foundation (ASF) under one
  19764. * or more contributor license agreements. See the NOTICE file
  19765. * distributed with this work for additional information
  19766. * regarding copyright ownership. The ASF licenses this file
  19767. * to you under the Apache License, Version 2.0 (the
  19768. * "License"); you may not use this file except in compliance
  19769. * with the License. You may obtain a copy of the License at
  19770. *
  19771. * http://www.apache.org/licenses/LICENSE-2.0
  19772. *
  19773. * Unless required by applicable law or agreed to in writing,
  19774. * software distributed under the License is distributed on an
  19775. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19776. * KIND, either express or implied. See the License for the
  19777. * specific language governing permissions and limitations
  19778. * under the License.
  19779. */
  19780. // (1) [Caution]: the logic is correct based on the premises:
  19781. // data processing stage is blocked in stream.
  19782. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  19783. // (2) Only register once when import repeatly.
  19784. // Should be executed before after series filtered and before stack calculation.
  19785. var dataStack = function (ecModel) {
  19786. var stackInfoMap = createHashMap();
  19787. ecModel.eachSeries(function (seriesModel) {
  19788. var stack = seriesModel.get('stack');
  19789. // Compatibal: when `stack` is set as '', do not stack.
  19790. if (stack) {
  19791. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  19792. var data = seriesModel.getData();
  19793. var stackInfo = {
  19794. // Used for calculate axis extent automatically.
  19795. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  19796. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  19797. stackedDimension: data.getCalculationInfo('stackedDimension'),
  19798. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  19799. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  19800. data: data,
  19801. seriesModel: seriesModel
  19802. };
  19803. // If stacked on axis that do not support data stack.
  19804. if (!stackInfo.stackedDimension
  19805. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  19806. ) {
  19807. return;
  19808. }
  19809. stackInfoList.length && data.setCalculationInfo(
  19810. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  19811. );
  19812. stackInfoList.push(stackInfo);
  19813. }
  19814. });
  19815. stackInfoMap.each(calculateStack);
  19816. };
  19817. function calculateStack(stackInfoList) {
  19818. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  19819. var resultVal = [];
  19820. var resultNaN = [NaN, NaN];
  19821. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  19822. var targetData = targetStackInfo.data;
  19823. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  19824. // Should not write on raw data, because stack series model list changes
  19825. // depending on legend selection.
  19826. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  19827. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  19828. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  19829. // should also be NaN, to draw a appropriate belt area.
  19830. if (isNaN(sum)) {
  19831. return resultNaN;
  19832. }
  19833. var byValue;
  19834. var stackedDataRawIndex;
  19835. if (isStackedByIndex) {
  19836. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  19837. }
  19838. else {
  19839. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  19840. }
  19841. // If stackOver is NaN, chart view will render point on value start.
  19842. var stackedOver = NaN;
  19843. for (var j = idxInStack - 1; j >= 0; j--) {
  19844. var stackInfo = stackInfoList[j];
  19845. // Has been optimized by inverted indices on `stackedByDimension`.
  19846. if (!isStackedByIndex) {
  19847. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19848. }
  19849. if (stackedDataRawIndex >= 0) {
  19850. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  19851. // Considering positive stack, negative stack and empty data
  19852. if ((sum >= 0 && val > 0) // Positive stack
  19853. || (sum <= 0 && val < 0) // Negative stack
  19854. ) {
  19855. sum += val;
  19856. stackedOver = val;
  19857. break;
  19858. }
  19859. }
  19860. }
  19861. resultVal[0] = sum;
  19862. resultVal[1] = stackedOver;
  19863. return resultVal;
  19864. });
  19865. targetData.hostModel.setData(newData);
  19866. // Update for consequent calculation
  19867. targetStackInfo.data = newData;
  19868. });
  19869. }
  19870. /*
  19871. * Licensed to the Apache Software Foundation (ASF) under one
  19872. * or more contributor license agreements. See the NOTICE file
  19873. * distributed with this work for additional information
  19874. * regarding copyright ownership. The ASF licenses this file
  19875. * to you under the Apache License, Version 2.0 (the
  19876. * "License"); you may not use this file except in compliance
  19877. * with the License. You may obtain a copy of the License at
  19878. *
  19879. * http://www.apache.org/licenses/LICENSE-2.0
  19880. *
  19881. * Unless required by applicable law or agreed to in writing,
  19882. * software distributed under the License is distributed on an
  19883. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19884. * KIND, either express or implied. See the License for the
  19885. * specific language governing permissions and limitations
  19886. * under the License.
  19887. */
  19888. // TODO
  19889. // ??? refactor? check the outer usage of data provider.
  19890. // merge with defaultDimValueGetter?
  19891. /**
  19892. * If normal array used, mutable chunk size is supported.
  19893. * If typed array used, chunk size must be fixed.
  19894. */
  19895. function DefaultDataProvider(source, dimSize) {
  19896. if (!Source.isInstance(source)) {
  19897. source = Source.seriesDataToSource(source);
  19898. }
  19899. this._source = source;
  19900. var data = this._data = source.data;
  19901. var sourceFormat = source.sourceFormat;
  19902. // Typed array. TODO IE10+?
  19903. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19904. if (__DEV__) {
  19905. if (dimSize == null) {
  19906. throw new Error('Typed array data must specify dimension size');
  19907. }
  19908. }
  19909. this._offset = 0;
  19910. this._dimSize = dimSize;
  19911. this._data = data;
  19912. }
  19913. var methods = providerMethods[
  19914. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  19915. ? sourceFormat + '_' + source.seriesLayoutBy
  19916. : sourceFormat
  19917. ];
  19918. if (__DEV__) {
  19919. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19920. }
  19921. extend(this, methods);
  19922. }
  19923. var providerProto = DefaultDataProvider.prototype;
  19924. // If data is pure without style configuration
  19925. providerProto.pure = false;
  19926. // If data is persistent and will not be released after use.
  19927. providerProto.persistent = true;
  19928. // ???! FIXME legacy data provider do not has method getSource
  19929. providerProto.getSource = function () {
  19930. return this._source;
  19931. };
  19932. var providerMethods = {
  19933. 'arrayRows_column': {
  19934. pure: true,
  19935. count: function () {
  19936. return Math.max(0, this._data.length - this._source.startIndex);
  19937. },
  19938. getItem: function (idx) {
  19939. return this._data[idx + this._source.startIndex];
  19940. },
  19941. appendData: appendDataSimply
  19942. },
  19943. 'arrayRows_row': {
  19944. pure: true,
  19945. count: function () {
  19946. var row = this._data[0];
  19947. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  19948. },
  19949. getItem: function (idx) {
  19950. idx += this._source.startIndex;
  19951. var item = [];
  19952. var data = this._data;
  19953. for (var i = 0; i < data.length; i++) {
  19954. var row = data[i];
  19955. item.push(row ? row[idx] : null);
  19956. }
  19957. return item;
  19958. },
  19959. appendData: function () {
  19960. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19961. }
  19962. },
  19963. 'objectRows': {
  19964. pure: true,
  19965. count: countSimply,
  19966. getItem: getItemSimply,
  19967. appendData: appendDataSimply
  19968. },
  19969. 'keyedColumns': {
  19970. pure: true,
  19971. count: function () {
  19972. var dimName = this._source.dimensionsDefine[0].name;
  19973. var col = this._data[dimName];
  19974. return col ? col.length : 0;
  19975. },
  19976. getItem: function (idx) {
  19977. var item = [];
  19978. var dims = this._source.dimensionsDefine;
  19979. for (var i = 0; i < dims.length; i++) {
  19980. var col = this._data[dims[i].name];
  19981. item.push(col ? col[idx] : null);
  19982. }
  19983. return item;
  19984. },
  19985. appendData: function (newData) {
  19986. var data = this._data;
  19987. each$1(newData, function (newCol, key) {
  19988. var oldCol = data[key] || (data[key] = []);
  19989. for (var i = 0; i < (newCol || []).length; i++) {
  19990. oldCol.push(newCol[i]);
  19991. }
  19992. });
  19993. }
  19994. },
  19995. 'original': {
  19996. count: countSimply,
  19997. getItem: getItemSimply,
  19998. appendData: appendDataSimply
  19999. },
  20000. 'typedArray': {
  20001. persistent: false,
  20002. pure: true,
  20003. count: function () {
  20004. return this._data ? (this._data.length / this._dimSize) : 0;
  20005. },
  20006. getItem: function (idx, out) {
  20007. idx = idx - this._offset;
  20008. out = out || [];
  20009. var offset = this._dimSize * idx;
  20010. for (var i = 0; i < this._dimSize; i++) {
  20011. out[i] = this._data[offset + i];
  20012. }
  20013. return out;
  20014. },
  20015. appendData: function (newData) {
  20016. if (__DEV__) {
  20017. assert$1(
  20018. isTypedArray(newData),
  20019. 'Added data must be TypedArray if data in initialization is TypedArray'
  20020. );
  20021. }
  20022. this._data = newData;
  20023. },
  20024. // Clean self if data is already used.
  20025. clean: function () {
  20026. // PENDING
  20027. this._offset += this.count();
  20028. this._data = null;
  20029. }
  20030. }
  20031. };
  20032. function countSimply() {
  20033. return this._data.length;
  20034. }
  20035. function getItemSimply(idx) {
  20036. return this._data[idx];
  20037. }
  20038. function appendDataSimply(newData) {
  20039. for (var i = 0; i < newData.length; i++) {
  20040. this._data.push(newData[i]);
  20041. }
  20042. }
  20043. var rawValueGetters = {
  20044. arrayRows: getRawValueSimply,
  20045. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  20046. return dimIndex != null ? dataItem[dimName] : dataItem;
  20047. },
  20048. keyedColumns: getRawValueSimply,
  20049. original: function (dataItem, dataIndex, dimIndex, dimName) {
  20050. // FIXME
  20051. // In some case (markpoint in geo (geo-map.html)), dataItem
  20052. // is {coord: [...]}
  20053. var value = getDataItemValue(dataItem);
  20054. return (dimIndex == null || !(value instanceof Array))
  20055. ? value
  20056. : value[dimIndex];
  20057. },
  20058. typedArray: getRawValueSimply
  20059. };
  20060. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  20061. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  20062. }
  20063. var defaultDimValueGetters = {
  20064. arrayRows: getDimValueSimply,
  20065. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  20066. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  20067. },
  20068. keyedColumns: getDimValueSimply,
  20069. original: function (dataItem, dimName, dataIndex, dimIndex) {
  20070. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20071. // If dataItem is an plain object with no value field, the var `value`
  20072. // will be assigned with the object, but it will be tread correctly
  20073. // in the `convertDataValue`.
  20074. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20075. // If any dataItem is like { value: 10 }
  20076. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  20077. this.hasItemOption = true;
  20078. }
  20079. return converDataValue(
  20080. (value instanceof Array)
  20081. ? value[dimIndex]
  20082. // If value is a single number or something else not array.
  20083. : value,
  20084. this._dimensionInfos[dimName]
  20085. );
  20086. },
  20087. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  20088. return dataItem[dimIndex];
  20089. }
  20090. };
  20091. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  20092. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  20093. }
  20094. /**
  20095. * This helper method convert value in data.
  20096. * @param {string|number|Date} value
  20097. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  20098. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  20099. */
  20100. function converDataValue(value, dimInfo) {
  20101. // Performance sensitive.
  20102. var dimType = dimInfo && dimInfo.type;
  20103. if (dimType === 'ordinal') {
  20104. // If given value is a category string
  20105. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  20106. return ordinalMeta
  20107. ? ordinalMeta.parseAndCollect(value)
  20108. : value;
  20109. }
  20110. if (dimType === 'time'
  20111. // spead up when using timestamp
  20112. && typeof value !== 'number'
  20113. && value != null
  20114. && value !== '-'
  20115. ) {
  20116. value = +parseDate(value);
  20117. }
  20118. // dimType defaults 'number'.
  20119. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20120. // parse to NaN.
  20121. return (value == null || value === '')
  20122. ? NaN
  20123. // If string (like '-'), using '+' parse to NaN
  20124. // If object, also parse to NaN
  20125. : +value;
  20126. }
  20127. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20128. // Consider persistent.
  20129. // Caution: why use raw value to display on label or tooltip?
  20130. // A reason is to avoid format. For example time value we do not know
  20131. // how to format is expected. More over, if stack is used, calculated
  20132. // value may be 0.91000000001, which have brings trouble to display.
  20133. // TODO: consider how to treat null/undefined/NaN when display?
  20134. /**
  20135. * @param {module:echarts/data/List} data
  20136. * @param {number} dataIndex
  20137. * @param {string|number} [dim] dimName or dimIndex
  20138. * @return {Array.<number>|string|number} can be null/undefined.
  20139. */
  20140. function retrieveRawValue(data, dataIndex, dim) {
  20141. if (!data) {
  20142. return;
  20143. }
  20144. // Consider data may be not persistent.
  20145. var dataItem = data.getRawDataItem(dataIndex);
  20146. if (dataItem == null) {
  20147. return;
  20148. }
  20149. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20150. var dimName;
  20151. var dimIndex;
  20152. var dimInfo = data.getDimensionInfo(dim);
  20153. if (dimInfo) {
  20154. dimName = dimInfo.name;
  20155. dimIndex = dimInfo.index;
  20156. }
  20157. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  20158. }
  20159. /**
  20160. * Compatible with some cases (in pie, map) like:
  20161. * data: [{name: 'xx', value: 5, selected: true}, ...]
  20162. * where only sourceFormat is 'original' and 'objectRows' supported.
  20163. *
  20164. * ??? TODO
  20165. * Supported detail options in data item when using 'arrayRows'.
  20166. *
  20167. * @param {module:echarts/data/List} data
  20168. * @param {number} dataIndex
  20169. * @param {string} attr like 'selected'
  20170. */
  20171. function retrieveRawAttr(data, dataIndex, attr) {
  20172. if (!data) {
  20173. return;
  20174. }
  20175. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20176. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  20177. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  20178. ) {
  20179. return;
  20180. }
  20181. var dataItem = data.getRawDataItem(dataIndex);
  20182. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  20183. dataItem = null;
  20184. }
  20185. if (dataItem) {
  20186. return dataItem[attr];
  20187. }
  20188. }
  20189. /*
  20190. * Licensed to the Apache Software Foundation (ASF) under one
  20191. * or more contributor license agreements. See the NOTICE file
  20192. * distributed with this work for additional information
  20193. * regarding copyright ownership. The ASF licenses this file
  20194. * to you under the Apache License, Version 2.0 (the
  20195. * "License"); you may not use this file except in compliance
  20196. * with the License. You may obtain a copy of the License at
  20197. *
  20198. * http://www.apache.org/licenses/LICENSE-2.0
  20199. *
  20200. * Unless required by applicable law or agreed to in writing,
  20201. * software distributed under the License is distributed on an
  20202. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20203. * KIND, either express or implied. See the License for the
  20204. * specific language governing permissions and limitations
  20205. * under the License.
  20206. */
  20207. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  20208. // PENDING A little ugly
  20209. var dataFormatMixin = {
  20210. /**
  20211. * Get params for formatter
  20212. * @param {number} dataIndex
  20213. * @param {string} [dataType]
  20214. * @return {Object}
  20215. */
  20216. getDataParams: function (dataIndex, dataType) {
  20217. var data = this.getData(dataType);
  20218. var rawValue = this.getRawValue(dataIndex, dataType);
  20219. var rawDataIndex = data.getRawIndex(dataIndex);
  20220. var name = data.getName(dataIndex);
  20221. var itemOpt = data.getRawDataItem(dataIndex);
  20222. var color = data.getItemVisual(dataIndex, 'color');
  20223. var tooltipModel = this.ecModel.getComponent('tooltip');
  20224. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  20225. var renderMode = getTooltipRenderMode(renderModeOption);
  20226. var mainType = this.mainType;
  20227. var isSeries = mainType === 'series';
  20228. return {
  20229. componentType: mainType,
  20230. componentSubType: this.subType,
  20231. componentIndex: this.componentIndex,
  20232. seriesType: isSeries ? this.subType : null,
  20233. seriesIndex: this.seriesIndex,
  20234. seriesId: isSeries ? this.id : null,
  20235. seriesName: isSeries ? this.name : null,
  20236. name: name,
  20237. dataIndex: rawDataIndex,
  20238. data: itemOpt,
  20239. dataType: dataType,
  20240. value: rawValue,
  20241. color: color,
  20242. marker: getTooltipMarker({
  20243. color: color,
  20244. renderMode: renderMode
  20245. }),
  20246. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  20247. $vars: ['seriesName', 'name', 'value']
  20248. };
  20249. },
  20250. /**
  20251. * Format label
  20252. * @param {number} dataIndex
  20253. * @param {string} [status='normal'] 'normal' or 'emphasis'
  20254. * @param {string} [dataType]
  20255. * @param {number} [dimIndex]
  20256. * @param {string} [labelProp='label']
  20257. * @return {string} If not formatter, return null/undefined
  20258. */
  20259. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  20260. status = status || 'normal';
  20261. var data = this.getData(dataType);
  20262. var itemModel = data.getItemModel(dataIndex);
  20263. var params = this.getDataParams(dataIndex, dataType);
  20264. if (dimIndex != null && (params.value instanceof Array)) {
  20265. params.value = params.value[dimIndex];
  20266. }
  20267. var formatter = itemModel.get(
  20268. status === 'normal'
  20269. ? [labelProp || 'label', 'formatter']
  20270. : [status, labelProp || 'label', 'formatter']
  20271. );
  20272. if (typeof formatter === 'function') {
  20273. params.status = status;
  20274. return formatter(params);
  20275. }
  20276. else if (typeof formatter === 'string') {
  20277. var str = formatTpl(formatter, params);
  20278. // Support 'aaa{@[3]}bbb{@product}ccc'.
  20279. // Do not support '}' in dim name util have to.
  20280. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  20281. var len = dim.length;
  20282. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  20283. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  20284. }
  20285. return retrieveRawValue(data, dataIndex, dim);
  20286. });
  20287. }
  20288. },
  20289. /**
  20290. * Get raw value in option
  20291. * @param {number} idx
  20292. * @param {string} [dataType]
  20293. * @return {Array|number|string}
  20294. */
  20295. getRawValue: function (idx, dataType) {
  20296. return retrieveRawValue(this.getData(dataType), idx);
  20297. },
  20298. /**
  20299. * Should be implemented.
  20300. * @param {number} dataIndex
  20301. * @param {boolean} [multipleSeries=false]
  20302. * @param {number} [dataType]
  20303. * @return {string} tooltip string
  20304. */
  20305. formatTooltip: function () {
  20306. // Empty function
  20307. }
  20308. };
  20309. /*
  20310. * Licensed to the Apache Software Foundation (ASF) under one
  20311. * or more contributor license agreements. See the NOTICE file
  20312. * distributed with this work for additional information
  20313. * regarding copyright ownership. The ASF licenses this file
  20314. * to you under the Apache License, Version 2.0 (the
  20315. * "License"); you may not use this file except in compliance
  20316. * with the License. You may obtain a copy of the License at
  20317. *
  20318. * http://www.apache.org/licenses/LICENSE-2.0
  20319. *
  20320. * Unless required by applicable law or agreed to in writing,
  20321. * software distributed under the License is distributed on an
  20322. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20323. * KIND, either express or implied. See the License for the
  20324. * specific language governing permissions and limitations
  20325. * under the License.
  20326. */
  20327. /**
  20328. * @param {Object} define
  20329. * @return See the return of `createTask`.
  20330. */
  20331. function createTask(define) {
  20332. return new Task(define);
  20333. }
  20334. /**
  20335. * @constructor
  20336. * @param {Object} define
  20337. * @param {Function} define.reset Custom reset
  20338. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  20339. * @param {Function} [define.count] count is used to determin data task.
  20340. * @param {Function} [define.onDirty] count is used to determin data task.
  20341. */
  20342. function Task(define) {
  20343. define = define || {};
  20344. this._reset = define.reset;
  20345. this._plan = define.plan;
  20346. this._count = define.count;
  20347. this._onDirty = define.onDirty;
  20348. this._dirty = true;
  20349. // Context must be specified implicitly, to
  20350. // avoid miss update context when model changed.
  20351. this.context;
  20352. }
  20353. var taskProto = Task.prototype;
  20354. /**
  20355. * @param {Object} performArgs
  20356. * @param {number} [performArgs.step] Specified step.
  20357. * @param {number} [performArgs.skip] Skip customer perform call.
  20358. * @param {number} [performArgs.modBy] Sampling window size.
  20359. * @param {number} [performArgs.modDataCount] Sampling count.
  20360. */
  20361. taskProto.perform = function (performArgs) {
  20362. var upTask = this._upstream;
  20363. var skip = performArgs && performArgs.skip;
  20364. // TODO some refactor.
  20365. // Pull data. Must pull data each time, because context.data
  20366. // may be updated by Series.setData.
  20367. if (this._dirty && upTask) {
  20368. var context = this.context;
  20369. context.data = context.outputData = upTask.context.outputData;
  20370. }
  20371. if (this.__pipeline) {
  20372. this.__pipeline.currentTask = this;
  20373. }
  20374. var planResult;
  20375. if (this._plan && !skip) {
  20376. planResult = this._plan(this.context);
  20377. }
  20378. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  20379. // elements uniformed distributed when progress, especially when moving or zooming.
  20380. var lastModBy = normalizeModBy(this._modBy);
  20381. var lastModDataCount = this._modDataCount || 0;
  20382. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  20383. var modDataCount = performArgs && performArgs.modDataCount || 0;
  20384. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  20385. planResult = 'reset';
  20386. }
  20387. function normalizeModBy(val) {
  20388. !(val >= 1) && (val = 1); // jshint ignore:line
  20389. return val;
  20390. }
  20391. var forceFirstProgress;
  20392. if (this._dirty || planResult === 'reset') {
  20393. this._dirty = false;
  20394. forceFirstProgress = reset(this, skip);
  20395. }
  20396. this._modBy = modBy;
  20397. this._modDataCount = modDataCount;
  20398. var step = performArgs && performArgs.step;
  20399. if (upTask) {
  20400. if (__DEV__) {
  20401. assert$1(upTask._outputDueEnd != null);
  20402. }
  20403. this._dueEnd = upTask._outputDueEnd;
  20404. }
  20405. // DataTask or overallTask
  20406. else {
  20407. if (__DEV__) {
  20408. assert$1(!this._progress || this._count);
  20409. }
  20410. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  20411. }
  20412. // Note: Stubs, that its host overall task let it has progress, has progress.
  20413. // If no progress, pass index from upstream to downstream each time plan called.
  20414. if (this._progress) {
  20415. var start = this._dueIndex;
  20416. var end = Math.min(
  20417. step != null ? this._dueIndex + step : Infinity,
  20418. this._dueEnd
  20419. );
  20420. if (!skip && (forceFirstProgress || start < end)) {
  20421. var progress = this._progress;
  20422. if (isArray(progress)) {
  20423. for (var i = 0; i < progress.length; i++) {
  20424. doProgress(this, progress[i], start, end, modBy, modDataCount);
  20425. }
  20426. }
  20427. else {
  20428. doProgress(this, progress, start, end, modBy, modDataCount);
  20429. }
  20430. }
  20431. this._dueIndex = end;
  20432. // If no `outputDueEnd`, assume that output data and
  20433. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  20434. var outputDueEnd = this._settedOutputEnd != null
  20435. ? this._settedOutputEnd : end;
  20436. if (__DEV__) {
  20437. // ??? Can not rollback.
  20438. assert$1(outputDueEnd >= this._outputDueEnd);
  20439. }
  20440. this._outputDueEnd = outputDueEnd;
  20441. }
  20442. else {
  20443. // (1) Some overall task has no progress.
  20444. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  20445. // This should always be performed so it can be passed to downstream.
  20446. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  20447. ? this._settedOutputEnd : this._dueEnd;
  20448. }
  20449. return this.unfinished();
  20450. };
  20451. var iterator = (function () {
  20452. var end;
  20453. var current;
  20454. var modBy;
  20455. var modDataCount;
  20456. var winCount;
  20457. var it = {
  20458. reset: function (s, e, sStep, sCount) {
  20459. current = s;
  20460. end = e;
  20461. modBy = sStep;
  20462. modDataCount = sCount;
  20463. winCount = Math.ceil(modDataCount / modBy);
  20464. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  20465. }
  20466. };
  20467. return it;
  20468. function sequentialNext() {
  20469. return current < end ? current++ : null;
  20470. }
  20471. function modNext() {
  20472. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  20473. var result = current >= end
  20474. ? null
  20475. : dataIndex < modDataCount
  20476. ? dataIndex
  20477. // If modDataCount is smaller than data.count() (consider `appendData` case),
  20478. // Use normal linear rendering mode.
  20479. : current;
  20480. current++;
  20481. return result;
  20482. }
  20483. })();
  20484. taskProto.dirty = function () {
  20485. this._dirty = true;
  20486. this._onDirty && this._onDirty(this.context);
  20487. };
  20488. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  20489. iterator.reset(start, end, modBy, modDataCount);
  20490. taskIns._callingProgress = progress;
  20491. taskIns._callingProgress({
  20492. start: start, end: end, count: end - start, next: iterator.next
  20493. }, taskIns.context);
  20494. }
  20495. function reset(taskIns, skip) {
  20496. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  20497. taskIns._settedOutputEnd = null;
  20498. var progress;
  20499. var forceFirstProgress;
  20500. if (!skip && taskIns._reset) {
  20501. progress = taskIns._reset(taskIns.context);
  20502. if (progress && progress.progress) {
  20503. forceFirstProgress = progress.forceFirstProgress;
  20504. progress = progress.progress;
  20505. }
  20506. // To simplify no progress checking, array must has item.
  20507. if (isArray(progress) && !progress.length) {
  20508. progress = null;
  20509. }
  20510. }
  20511. taskIns._progress = progress;
  20512. taskIns._modBy = taskIns._modDataCount = null;
  20513. var downstream = taskIns._downstream;
  20514. downstream && downstream.dirty();
  20515. return forceFirstProgress;
  20516. }
  20517. /**
  20518. * @return {boolean}
  20519. */
  20520. taskProto.unfinished = function () {
  20521. return this._progress && this._dueIndex < this._dueEnd;
  20522. };
  20523. /**
  20524. * @param {Object} downTask The downstream task.
  20525. * @return {Object} The downstream task.
  20526. */
  20527. taskProto.pipe = function (downTask) {
  20528. if (__DEV__) {
  20529. assert$1(downTask && !downTask._disposed && downTask !== this);
  20530. }
  20531. // If already downstream, do not dirty downTask.
  20532. if (this._downstream !== downTask || this._dirty) {
  20533. this._downstream = downTask;
  20534. downTask._upstream = this;
  20535. downTask.dirty();
  20536. }
  20537. };
  20538. taskProto.dispose = function () {
  20539. if (this._disposed) {
  20540. return;
  20541. }
  20542. this._upstream && (this._upstream._downstream = null);
  20543. this._downstream && (this._downstream._upstream = null);
  20544. this._dirty = false;
  20545. this._disposed = true;
  20546. };
  20547. taskProto.getUpstream = function () {
  20548. return this._upstream;
  20549. };
  20550. taskProto.getDownstream = function () {
  20551. return this._downstream;
  20552. };
  20553. taskProto.setOutputEnd = function (end) {
  20554. // This only happend in dataTask, dataZoom, map, currently.
  20555. // where dataZoom do not set end each time, but only set
  20556. // when reset. So we should record the setted end, in case
  20557. // that the stub of dataZoom perform again and earse the
  20558. // setted end by upstream.
  20559. this._outputDueEnd = this._settedOutputEnd = end;
  20560. };
  20561. ///////////////////////////////////////////////////////////
  20562. // For stream debug (Should be commented out after used!)
  20563. // Usage: printTask(this, 'begin');
  20564. // Usage: printTask(this, null, {someExtraProp});
  20565. // function printTask(task, prefix, extra) {
  20566. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  20567. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  20568. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  20569. // var props = [];
  20570. // if (task.__pipeline) {
  20571. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  20572. // props.push({text: 'idx', value: val});
  20573. // } else {
  20574. // var stubCount = 0;
  20575. // task.agentStubMap.each(() => stubCount++);
  20576. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  20577. // }
  20578. // props.push({text: 'uid', value: task.uidDebug});
  20579. // if (task.__pipeline) {
  20580. // props.push({text: 'pid', value: task.__pipeline.id});
  20581. // task.agent && props.push(
  20582. // {text: 'stubFor', value: task.agent.uidDebug}
  20583. // );
  20584. // }
  20585. // props.push(
  20586. // {text: 'dirty', value: task._dirty},
  20587. // {text: 'dueIndex', value: task._dueIndex},
  20588. // {text: 'dueEnd', value: task._dueEnd},
  20589. // {text: 'outputDueEnd', value: task._outputDueEnd}
  20590. // );
  20591. // if (extra) {
  20592. // Object.keys(extra).forEach(key => {
  20593. // props.push({text: key, value: extra[key]});
  20594. // });
  20595. // }
  20596. // var args = ['color: blue'];
  20597. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  20598. // args.push('color: black', 'color: red'),
  20599. // `${item.text}: %c${item.value}`
  20600. // )).join('%c, ');
  20601. // console.log.apply(console, [msg].concat(args));
  20602. // // console.log(this);
  20603. // }
  20604. /*
  20605. * Licensed to the Apache Software Foundation (ASF) under one
  20606. * or more contributor license agreements. See the NOTICE file
  20607. * distributed with this work for additional information
  20608. * regarding copyright ownership. The ASF licenses this file
  20609. * to you under the Apache License, Version 2.0 (the
  20610. * "License"); you may not use this file except in compliance
  20611. * with the License. You may obtain a copy of the License at
  20612. *
  20613. * http://www.apache.org/licenses/LICENSE-2.0
  20614. *
  20615. * Unless required by applicable law or agreed to in writing,
  20616. * software distributed under the License is distributed on an
  20617. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20618. * KIND, either express or implied. See the License for the
  20619. * specific language governing permissions and limitations
  20620. * under the License.
  20621. */
  20622. var inner$4 = makeInner();
  20623. var SeriesModel = ComponentModel.extend({
  20624. type: 'series.__base__',
  20625. /**
  20626. * @readOnly
  20627. */
  20628. seriesIndex: 0,
  20629. // coodinateSystem will be injected in the echarts/CoordinateSystem
  20630. coordinateSystem: null,
  20631. /**
  20632. * @type {Object}
  20633. * @protected
  20634. */
  20635. defaultOption: null,
  20636. /**
  20637. * Data provided for legend
  20638. * @type {Function}
  20639. */
  20640. // PENDING
  20641. legendDataProvider: null,
  20642. /**
  20643. * Access path of color for visual
  20644. */
  20645. visualColorAccessPath: 'itemStyle.color',
  20646. /**
  20647. * Support merge layout params.
  20648. * Only support 'box' now (left/right/top/bottom/width/height).
  20649. * @type {string|Object} Object can be {ignoreSize: true}
  20650. * @readOnly
  20651. */
  20652. layoutMode: null,
  20653. init: function (option, parentModel, ecModel, extraOpt) {
  20654. /**
  20655. * @type {number}
  20656. * @readOnly
  20657. */
  20658. this.seriesIndex = this.componentIndex;
  20659. this.dataTask = createTask({
  20660. count: dataTaskCount,
  20661. reset: dataTaskReset
  20662. });
  20663. this.dataTask.context = {model: this};
  20664. this.mergeDefaultAndTheme(option, ecModel);
  20665. prepareSource(this);
  20666. var data = this.getInitialData(option, ecModel);
  20667. wrapData(data, this);
  20668. this.dataTask.context.data = data;
  20669. if (__DEV__) {
  20670. assert$1(data, 'getInitialData returned invalid data.');
  20671. }
  20672. /**
  20673. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  20674. * @private
  20675. */
  20676. inner$4(this).dataBeforeProcessed = data;
  20677. // If we reverse the order (make data firstly, and then make
  20678. // dataBeforeProcessed by cloneShallow), cloneShallow will
  20679. // cause data.graph.data !== data when using
  20680. // module:echarts/data/Graph or module:echarts/data/Tree.
  20681. // See module:echarts/data/helper/linkList
  20682. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  20683. // init or merge stage, because the data can be restored. So we do not `restoreData`
  20684. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  20685. // Call `seriesModel.getRawData()` instead.
  20686. // this.restoreData();
  20687. autoSeriesName(this);
  20688. },
  20689. /**
  20690. * Util for merge default and theme to option
  20691. * @param {Object} option
  20692. * @param {module:echarts/model/Global} ecModel
  20693. */
  20694. mergeDefaultAndTheme: function (option, ecModel) {
  20695. var layoutMode = this.layoutMode;
  20696. var inputPositionParams = layoutMode
  20697. ? getLayoutParams(option) : {};
  20698. // Backward compat: using subType on theme.
  20699. // But if name duplicate between series subType
  20700. // (for example: parallel) add component mainType,
  20701. // add suffix 'Series'.
  20702. var themeSubType = this.subType;
  20703. if (ComponentModel.hasClass(themeSubType)) {
  20704. themeSubType += 'Series';
  20705. }
  20706. merge(
  20707. option,
  20708. ecModel.getTheme().get(this.subType)
  20709. );
  20710. merge(option, this.getDefaultOption());
  20711. // Default label emphasis `show`
  20712. defaultEmphasis(option, 'label', ['show']);
  20713. this.fillDataTextStyle(option.data);
  20714. if (layoutMode) {
  20715. mergeLayoutParam(option, inputPositionParams, layoutMode);
  20716. }
  20717. },
  20718. mergeOption: function (newSeriesOption, ecModel) {
  20719. // this.settingTask.dirty();
  20720. newSeriesOption = merge(this.option, newSeriesOption, true);
  20721. this.fillDataTextStyle(newSeriesOption.data);
  20722. var layoutMode = this.layoutMode;
  20723. if (layoutMode) {
  20724. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  20725. }
  20726. prepareSource(this);
  20727. var data = this.getInitialData(newSeriesOption, ecModel);
  20728. wrapData(data, this);
  20729. this.dataTask.dirty();
  20730. this.dataTask.context.data = data;
  20731. inner$4(this).dataBeforeProcessed = data;
  20732. autoSeriesName(this);
  20733. },
  20734. fillDataTextStyle: function (data) {
  20735. // Default data label emphasis `show`
  20736. // FIXME Tree structure data ?
  20737. // FIXME Performance ?
  20738. if (data && !isTypedArray(data)) {
  20739. var props = ['show'];
  20740. for (var i = 0; i < data.length; i++) {
  20741. if (data[i] && data[i].label) {
  20742. defaultEmphasis(data[i], 'label', props);
  20743. }
  20744. }
  20745. }
  20746. },
  20747. /**
  20748. * Init a data structure from data related option in series
  20749. * Must be overwritten
  20750. */
  20751. getInitialData: function () {},
  20752. /**
  20753. * Append data to list
  20754. * @param {Object} params
  20755. * @param {Array|TypedArray} params.data
  20756. */
  20757. appendData: function (params) {
  20758. // FIXME ???
  20759. // (1) If data from dataset, forbidden append.
  20760. // (2) support append data of dataset.
  20761. var data = this.getRawData();
  20762. data.appendData(params.data);
  20763. },
  20764. /**
  20765. * Consider some method like `filter`, `map` need make new data,
  20766. * We should make sure that `seriesModel.getData()` get correct
  20767. * data in the stream procedure. So we fetch data from upstream
  20768. * each time `task.perform` called.
  20769. * @param {string} [dataType]
  20770. * @return {module:echarts/data/List}
  20771. */
  20772. getData: function (dataType) {
  20773. var task = getCurrentTask(this);
  20774. if (task) {
  20775. var data = task.context.data;
  20776. return dataType == null ? data : data.getLinkedData(dataType);
  20777. }
  20778. else {
  20779. // When series is not alive (that may happen when click toolbox
  20780. // restore or setOption with not merge mode), series data may
  20781. // be still need to judge animation or something when graphic
  20782. // elements want to know whether fade out.
  20783. return inner$4(this).data;
  20784. }
  20785. },
  20786. /**
  20787. * @param {module:echarts/data/List} data
  20788. */
  20789. setData: function (data) {
  20790. var task = getCurrentTask(this);
  20791. if (task) {
  20792. var context = task.context;
  20793. // Consider case: filter, data sample.
  20794. if (context.data !== data && task.modifyOutputEnd) {
  20795. task.setOutputEnd(data.count());
  20796. }
  20797. context.outputData = data;
  20798. // Caution: setData should update context.data,
  20799. // Because getData may be called multiply in a
  20800. // single stage and expect to get the data just
  20801. // set. (For example, AxisProxy, x y both call
  20802. // getData and setDate sequentially).
  20803. // So the context.data should be fetched from
  20804. // upstream each time when a stage starts to be
  20805. // performed.
  20806. if (task !== this.dataTask) {
  20807. context.data = data;
  20808. }
  20809. }
  20810. inner$4(this).data = data;
  20811. },
  20812. /**
  20813. * @see {module:echarts/data/helper/sourceHelper#getSource}
  20814. * @return {module:echarts/data/Source} source
  20815. */
  20816. getSource: function () {
  20817. return getSource(this);
  20818. },
  20819. /**
  20820. * Get data before processed
  20821. * @return {module:echarts/data/List}
  20822. */
  20823. getRawData: function () {
  20824. return inner$4(this).dataBeforeProcessed;
  20825. },
  20826. /**
  20827. * Get base axis if has coordinate system and has axis.
  20828. * By default use coordSys.getBaseAxis();
  20829. * Can be overrided for some chart.
  20830. * @return {type} description
  20831. */
  20832. getBaseAxis: function () {
  20833. var coordSys = this.coordinateSystem;
  20834. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  20835. },
  20836. // FIXME
  20837. /**
  20838. * Default tooltip formatter
  20839. *
  20840. * @param {number} dataIndex
  20841. * @param {boolean} [multipleSeries=false]
  20842. * @param {number} [dataType]
  20843. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  20844. * 'html' is used for rendering tooltip in extra DOM form, and the result
  20845. * string is used as DOM HTML content.
  20846. * 'richText' is used for rendering tooltip in rich text form, for those where
  20847. * DOM operation is not supported.
  20848. * @return {Object} formatted tooltip with `html` and `markers`
  20849. */
  20850. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  20851. var series = this;
  20852. renderMode = renderMode || 'html';
  20853. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  20854. var isRichText = renderMode === 'richText';
  20855. var markers = {};
  20856. var markerId = 0;
  20857. function formatArrayValue(value) {
  20858. // ??? TODO refactor these logic.
  20859. // check: category-no-encode-has-axis-data in dataset.html
  20860. var vertially = reduce(value, function (vertially, val, idx) {
  20861. var dimItem = data.getDimensionInfo(idx);
  20862. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20863. }, 0);
  20864. var result = [];
  20865. tooltipDims.length
  20866. ? each$1(tooltipDims, function (dim) {
  20867. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20868. })
  20869. // By default, all dims is used on tooltip.
  20870. : each$1(value, setEachItem);
  20871. function setEachItem(val, dim) {
  20872. var dimInfo = data.getDimensionInfo(dim);
  20873. // If `dimInfo.tooltip` is not set, show tooltip.
  20874. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20875. return;
  20876. }
  20877. var dimType = dimInfo.type;
  20878. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  20879. var dimHead = getTooltipMarker({
  20880. color: color,
  20881. type: 'subItem',
  20882. renderMode: renderMode,
  20883. markerId: markName
  20884. });
  20885. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  20886. var valStr = (vertially
  20887. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  20888. : ''
  20889. )
  20890. // FIXME should not format time for raw data?
  20891. + encodeHTML(dimType === 'ordinal'
  20892. ? val + ''
  20893. : dimType === 'time'
  20894. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  20895. : addCommas(val)
  20896. );
  20897. valStr && result.push(valStr);
  20898. if (isRichText) {
  20899. markers[markName] = color;
  20900. ++markerId;
  20901. }
  20902. }
  20903. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  20904. var content = newLine + result.join(newLine || ', ');
  20905. return {
  20906. renderMode: renderMode,
  20907. content: content,
  20908. style: markers
  20909. };
  20910. }
  20911. function formatSingleValue(val) {
  20912. // return encodeHTML(addCommas(val));
  20913. return {
  20914. renderMode: renderMode,
  20915. content: encodeHTML(addCommas(val)),
  20916. style: markers
  20917. };
  20918. }
  20919. var data = this.getData();
  20920. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  20921. var tooltipDimLen = tooltipDims.length;
  20922. var value = this.getRawValue(dataIndex);
  20923. var isValueArr = isArray(value);
  20924. var color = data.getItemVisual(dataIndex, 'color');
  20925. if (isObject$1(color) && color.colorStops) {
  20926. color = (color.colorStops[0] || {}).color;
  20927. }
  20928. color = color || 'transparent';
  20929. // Complicated rule for pretty tooltip.
  20930. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  20931. ? formatArrayValue(value)
  20932. : tooltipDimLen
  20933. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  20934. : formatSingleValue(isValueArr ? value[0] : value);
  20935. var content = formattedValue.content;
  20936. var markName = series.seriesIndex + 'at' + markerId;
  20937. var colorEl = getTooltipMarker({
  20938. color: color,
  20939. type: 'item',
  20940. renderMode: renderMode,
  20941. markerId: markName
  20942. });
  20943. markers[markName] = color;
  20944. ++markerId;
  20945. var name = data.getName(dataIndex);
  20946. var seriesName = this.name;
  20947. if (!isNameSpecified(this)) {
  20948. seriesName = '';
  20949. }
  20950. seriesName = seriesName
  20951. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  20952. : '';
  20953. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  20954. var html = !multipleSeries
  20955. ? seriesName + colorStr
  20956. + (name
  20957. ? encodeHTML(name) + ': ' + content
  20958. : content
  20959. )
  20960. : colorStr + seriesName + content;
  20961. return {
  20962. html: html,
  20963. markers: markers
  20964. };
  20965. },
  20966. /**
  20967. * @return {boolean}
  20968. */
  20969. isAnimationEnabled: function () {
  20970. if (env$1.node) {
  20971. return false;
  20972. }
  20973. var animationEnabled = this.getShallow('animation');
  20974. if (animationEnabled) {
  20975. if (this.getData().count() > this.getShallow('animationThreshold')) {
  20976. animationEnabled = false;
  20977. }
  20978. }
  20979. return animationEnabled;
  20980. },
  20981. restoreData: function () {
  20982. this.dataTask.dirty();
  20983. },
  20984. getColorFromPalette: function (name, scope, requestColorNum) {
  20985. var ecModel = this.ecModel;
  20986. // PENDING
  20987. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  20988. if (!color) {
  20989. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  20990. }
  20991. return color;
  20992. },
  20993. /**
  20994. * Use `data.mapDimension(coordDim, true)` instead.
  20995. * @deprecated
  20996. */
  20997. coordDimToDataDim: function (coordDim) {
  20998. return this.getRawData().mapDimension(coordDim, true);
  20999. },
  21000. /**
  21001. * Get progressive rendering count each step
  21002. * @return {number}
  21003. */
  21004. getProgressive: function () {
  21005. return this.get('progressive');
  21006. },
  21007. /**
  21008. * Get progressive rendering count each step
  21009. * @return {number}
  21010. */
  21011. getProgressiveThreshold: function () {
  21012. return this.get('progressiveThreshold');
  21013. },
  21014. /**
  21015. * Get data indices for show tooltip content. See tooltip.
  21016. * @abstract
  21017. * @param {Array.<string>|string} dim
  21018. * @param {Array.<number>} value
  21019. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  21020. * @return {Object} {dataIndices, nestestValue}.
  21021. */
  21022. getAxisTooltipData: null,
  21023. /**
  21024. * See tooltip.
  21025. * @abstract
  21026. * @param {number} dataIndex
  21027. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  21028. */
  21029. getTooltipPosition: null,
  21030. /**
  21031. * @see {module:echarts/stream/Scheduler}
  21032. */
  21033. pipeTask: null,
  21034. /**
  21035. * Convinient for override in extended class.
  21036. * @protected
  21037. * @type {Function}
  21038. */
  21039. preventIncremental: null,
  21040. /**
  21041. * @public
  21042. * @readOnly
  21043. * @type {Object}
  21044. */
  21045. pipelineContext: null
  21046. });
  21047. mixin(SeriesModel, dataFormatMixin);
  21048. mixin(SeriesModel, colorPaletteMixin);
  21049. /**
  21050. * MUST be called after `prepareSource` called
  21051. * Here we need to make auto series, especially for auto legend. But we
  21052. * do not modify series.name in option to avoid side effects.
  21053. */
  21054. function autoSeriesName(seriesModel) {
  21055. // User specified name has higher priority, otherwise it may cause
  21056. // series can not be queried unexpectedly.
  21057. var name = seriesModel.name;
  21058. if (!isNameSpecified(seriesModel)) {
  21059. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21060. }
  21061. }
  21062. function getSeriesAutoName(seriesModel) {
  21063. var data = seriesModel.getRawData();
  21064. var dataDims = data.mapDimension('seriesName', true);
  21065. var nameArr = [];
  21066. each$1(dataDims, function (dataDim) {
  21067. var dimInfo = data.getDimensionInfo(dataDim);
  21068. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21069. });
  21070. return nameArr.join(' ');
  21071. }
  21072. function dataTaskCount(context) {
  21073. return context.model.getRawData().count();
  21074. }
  21075. function dataTaskReset(context) {
  21076. var seriesModel = context.model;
  21077. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21078. return dataTaskProgress;
  21079. }
  21080. function dataTaskProgress(param, context) {
  21081. // Avoid repead cloneShallow when data just created in reset.
  21082. if (param.end > context.outputData.count()) {
  21083. context.model.getRawData().cloneShallow(context.outputData);
  21084. }
  21085. }
  21086. // TODO refactor
  21087. function wrapData(data, seriesModel) {
  21088. each$1(data.CHANGABLE_METHODS, function (methodName) {
  21089. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  21090. });
  21091. }
  21092. function onDataSelfChange(seriesModel) {
  21093. var task = getCurrentTask(seriesModel);
  21094. if (task) {
  21095. // Consider case: filter, selectRange
  21096. task.setOutputEnd(this.count());
  21097. }
  21098. }
  21099. function getCurrentTask(seriesModel) {
  21100. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21101. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21102. if (pipeline) {
  21103. // When pipline finished, the currrentTask keep the last
  21104. // task (renderTask).
  21105. var task = pipeline.currentTask;
  21106. if (task) {
  21107. var agentStubMap = task.agentStubMap;
  21108. if (agentStubMap) {
  21109. task = agentStubMap.get(seriesModel.uid);
  21110. }
  21111. }
  21112. return task;
  21113. }
  21114. }
  21115. /*
  21116. * Licensed to the Apache Software Foundation (ASF) under one
  21117. * or more contributor license agreements. See the NOTICE file
  21118. * distributed with this work for additional information
  21119. * regarding copyright ownership. The ASF licenses this file
  21120. * to you under the Apache License, Version 2.0 (the
  21121. * "License"); you may not use this file except in compliance
  21122. * with the License. You may obtain a copy of the License at
  21123. *
  21124. * http://www.apache.org/licenses/LICENSE-2.0
  21125. *
  21126. * Unless required by applicable law or agreed to in writing,
  21127. * software distributed under the License is distributed on an
  21128. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21129. * KIND, either express or implied. See the License for the
  21130. * specific language governing permissions and limitations
  21131. * under the License.
  21132. */
  21133. var Component = function () {
  21134. /**
  21135. * @type {module:zrender/container/Group}
  21136. * @readOnly
  21137. */
  21138. this.group = new Group();
  21139. /**
  21140. * @type {string}
  21141. * @readOnly
  21142. */
  21143. this.uid = getUID('viewComponent');
  21144. };
  21145. Component.prototype = {
  21146. constructor: Component,
  21147. init: function (ecModel, api) {},
  21148. render: function (componentModel, ecModel, api, payload) {},
  21149. dispose: function () {},
  21150. /**
  21151. * @param {string} eventType
  21152. * @param {Object} query
  21153. * @param {module:zrender/Element} targetEl
  21154. * @param {Object} packedEvent
  21155. * @return {boolen} Pass only when return `true`.
  21156. */
  21157. filterForExposedEvent: null
  21158. };
  21159. var componentProto = Component.prototype;
  21160. componentProto.updateView
  21161. = componentProto.updateLayout
  21162. = componentProto.updateVisual
  21163. = function (seriesModel, ecModel, api, payload) {
  21164. // Do nothing;
  21165. };
  21166. // Enable Component.extend.
  21167. enableClassExtend(Component);
  21168. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21169. enableClassManagement(Component, {registerWhenExtend: true});
  21170. /*
  21171. * Licensed to the Apache Software Foundation (ASF) under one
  21172. * or more contributor license agreements. See the NOTICE file
  21173. * distributed with this work for additional information
  21174. * regarding copyright ownership. The ASF licenses this file
  21175. * to you under the Apache License, Version 2.0 (the
  21176. * "License"); you may not use this file except in compliance
  21177. * with the License. You may obtain a copy of the License at
  21178. *
  21179. * http://www.apache.org/licenses/LICENSE-2.0
  21180. *
  21181. * Unless required by applicable law or agreed to in writing,
  21182. * software distributed under the License is distributed on an
  21183. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21184. * KIND, either express or implied. See the License for the
  21185. * specific language governing permissions and limitations
  21186. * under the License.
  21187. */
  21188. /**
  21189. * @return {string} If large mode changed, return string 'reset';
  21190. */
  21191. var createRenderPlanner = function () {
  21192. var inner = makeInner();
  21193. return function (seriesModel) {
  21194. var fields = inner(seriesModel);
  21195. var pipelineContext = seriesModel.pipelineContext;
  21196. var originalLarge = fields.large;
  21197. var originalProgressive = fields.progressiveRender;
  21198. var large = fields.large = pipelineContext.large;
  21199. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  21200. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  21201. };
  21202. };
  21203. /*
  21204. * Licensed to the Apache Software Foundation (ASF) under one
  21205. * or more contributor license agreements. See the NOTICE file
  21206. * distributed with this work for additional information
  21207. * regarding copyright ownership. The ASF licenses this file
  21208. * to you under the Apache License, Version 2.0 (the
  21209. * "License"); you may not use this file except in compliance
  21210. * with the License. You may obtain a copy of the License at
  21211. *
  21212. * http://www.apache.org/licenses/LICENSE-2.0
  21213. *
  21214. * Unless required by applicable law or agreed to in writing,
  21215. * software distributed under the License is distributed on an
  21216. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21217. * KIND, either express or implied. See the License for the
  21218. * specific language governing permissions and limitations
  21219. * under the License.
  21220. */
  21221. var inner$5 = makeInner();
  21222. var renderPlanner = createRenderPlanner();
  21223. function Chart() {
  21224. /**
  21225. * @type {module:zrender/container/Group}
  21226. * @readOnly
  21227. */
  21228. this.group = new Group();
  21229. /**
  21230. * @type {string}
  21231. * @readOnly
  21232. */
  21233. this.uid = getUID('viewChart');
  21234. this.renderTask = createTask({
  21235. plan: renderTaskPlan,
  21236. reset: renderTaskReset
  21237. });
  21238. this.renderTask.context = {view: this};
  21239. }
  21240. Chart.prototype = {
  21241. type: 'chart',
  21242. /**
  21243. * Init the chart.
  21244. * @param {module:echarts/model/Global} ecModel
  21245. * @param {module:echarts/ExtensionAPI} api
  21246. */
  21247. init: function (ecModel, api) {},
  21248. /**
  21249. * Render the chart.
  21250. * @param {module:echarts/model/Series} seriesModel
  21251. * @param {module:echarts/model/Global} ecModel
  21252. * @param {module:echarts/ExtensionAPI} api
  21253. * @param {Object} payload
  21254. */
  21255. render: function (seriesModel, ecModel, api, payload) {},
  21256. /**
  21257. * Highlight series or specified data item.
  21258. * @param {module:echarts/model/Series} seriesModel
  21259. * @param {module:echarts/model/Global} ecModel
  21260. * @param {module:echarts/ExtensionAPI} api
  21261. * @param {Object} payload
  21262. */
  21263. highlight: function (seriesModel, ecModel, api, payload) {
  21264. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  21265. },
  21266. /**
  21267. * Downplay series or specified data item.
  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. */
  21273. downplay: function (seriesModel, ecModel, api, payload) {
  21274. toggleHighlight(seriesModel.getData(), payload, 'normal');
  21275. },
  21276. /**
  21277. * Remove self.
  21278. * @param {module:echarts/model/Global} ecModel
  21279. * @param {module:echarts/ExtensionAPI} api
  21280. */
  21281. remove: function (ecModel, api) {
  21282. this.group.removeAll();
  21283. },
  21284. /**
  21285. * Dispose self.
  21286. * @param {module:echarts/model/Global} ecModel
  21287. * @param {module:echarts/ExtensionAPI} api
  21288. */
  21289. dispose: function () {},
  21290. /**
  21291. * Rendering preparation in progressive mode.
  21292. * @param {module:echarts/model/Series} seriesModel
  21293. * @param {module:echarts/model/Global} ecModel
  21294. * @param {module:echarts/ExtensionAPI} api
  21295. * @param {Object} payload
  21296. */
  21297. incrementalPrepareRender: null,
  21298. /**
  21299. * Render in progressive mode.
  21300. * @param {Object} params See taskParams in `stream/task.js`
  21301. * @param {module:echarts/model/Series} seriesModel
  21302. * @param {module:echarts/model/Global} ecModel
  21303. * @param {module:echarts/ExtensionAPI} api
  21304. * @param {Object} payload
  21305. */
  21306. incrementalRender: null,
  21307. /**
  21308. * Update transform directly.
  21309. * @param {module:echarts/model/Series} seriesModel
  21310. * @param {module:echarts/model/Global} ecModel
  21311. * @param {module:echarts/ExtensionAPI} api
  21312. * @param {Object} payload
  21313. * @return {Object} {update: true}
  21314. */
  21315. updateTransform: null,
  21316. /**
  21317. * The view contains the given point.
  21318. * @interface
  21319. * @param {Array.<number>} point
  21320. * @return {boolean}
  21321. */
  21322. // containPoint: function () {}
  21323. /**
  21324. * @param {string} eventType
  21325. * @param {Object} query
  21326. * @param {module:zrender/Element} targetEl
  21327. * @param {Object} packedEvent
  21328. * @return {boolen} Pass only when return `true`.
  21329. */
  21330. filterForExposedEvent: null
  21331. };
  21332. var chartProto = Chart.prototype;
  21333. chartProto.updateView
  21334. = chartProto.updateLayout
  21335. = chartProto.updateVisual
  21336. = function (seriesModel, ecModel, api, payload) {
  21337. this.render(seriesModel, ecModel, api, payload);
  21338. };
  21339. /**
  21340. * Set state of single element
  21341. * @param {module:zrender/Element} el
  21342. * @param {string} state
  21343. */
  21344. function elSetState(el, state) {
  21345. if (el) {
  21346. el.trigger(state);
  21347. if (el.type === 'group') {
  21348. for (var i = 0; i < el.childCount(); i++) {
  21349. elSetState(el.childAt(i), state);
  21350. }
  21351. }
  21352. }
  21353. }
  21354. /**
  21355. * @param {module:echarts/data/List} data
  21356. * @param {Object} payload
  21357. * @param {string} state 'normal'|'emphasis'
  21358. */
  21359. function toggleHighlight(data, payload, state) {
  21360. var dataIndex = queryDataIndex(data, payload);
  21361. if (dataIndex != null) {
  21362. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  21363. elSetState(data.getItemGraphicEl(dataIdx), state);
  21364. });
  21365. }
  21366. else {
  21367. data.eachItemGraphicEl(function (el) {
  21368. elSetState(el, state);
  21369. });
  21370. }
  21371. }
  21372. // Enable Chart.extend.
  21373. enableClassExtend(Chart, ['dispose']);
  21374. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21375. enableClassManagement(Chart, {registerWhenExtend: true});
  21376. Chart.markUpdateMethod = function (payload, methodName) {
  21377. inner$5(payload).updateMethod = methodName;
  21378. };
  21379. function renderTaskPlan(context) {
  21380. return renderPlanner(context.model);
  21381. }
  21382. function renderTaskReset(context) {
  21383. var seriesModel = context.model;
  21384. var ecModel = context.ecModel;
  21385. var api = context.api;
  21386. var payload = context.payload;
  21387. // ???! remove updateView updateVisual
  21388. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  21389. var view = context.view;
  21390. var updateMethod = payload && inner$5(payload).updateMethod;
  21391. var methodName = progressiveRender
  21392. ? 'incrementalPrepareRender'
  21393. : (updateMethod && view[updateMethod])
  21394. ? updateMethod
  21395. // `appendData` is also supported when data amount
  21396. // is less than progressive threshold.
  21397. : 'render';
  21398. if (methodName !== 'render') {
  21399. view[methodName](seriesModel, ecModel, api, payload);
  21400. }
  21401. return progressMethodMap[methodName];
  21402. }
  21403. var progressMethodMap = {
  21404. incrementalPrepareRender: {
  21405. progress: function (params, context) {
  21406. context.view.incrementalRender(
  21407. params, context.model, context.ecModel, context.api, context.payload
  21408. );
  21409. }
  21410. },
  21411. render: {
  21412. // Put view.render in `progress` to support appendData. But in this case
  21413. // view.render should not be called in reset, otherwise it will be called
  21414. // twise. Use `forceFirstProgress` to make sure that view.render is called
  21415. // in any cases.
  21416. forceFirstProgress: true,
  21417. progress: function (params, context) {
  21418. context.view.render(
  21419. context.model, context.ecModel, context.api, context.payload
  21420. );
  21421. }
  21422. }
  21423. };
  21424. /*
  21425. * Licensed to the Apache Software Foundation (ASF) under one
  21426. * or more contributor license agreements. See the NOTICE file
  21427. * distributed with this work for additional information
  21428. * regarding copyright ownership. The ASF licenses this file
  21429. * to you under the Apache License, Version 2.0 (the
  21430. * "License"); you may not use this file except in compliance
  21431. * with the License. You may obtain a copy of the License at
  21432. *
  21433. * http://www.apache.org/licenses/LICENSE-2.0
  21434. *
  21435. * Unless required by applicable law or agreed to in writing,
  21436. * software distributed under the License is distributed on an
  21437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21438. * KIND, either express or implied. See the License for the
  21439. * specific language governing permissions and limitations
  21440. * under the License.
  21441. */
  21442. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  21443. var RATE = '\0__throttleRate';
  21444. var THROTTLE_TYPE = '\0__throttleType';
  21445. /**
  21446. * @public
  21447. * @param {(Function)} fn
  21448. * @param {number} [delay=0] Unit: ms.
  21449. * @param {boolean} [debounce=false]
  21450. * true: If call interval less than `delay`, only the last call works.
  21451. * false: If call interval less than `delay, call works on fixed rate.
  21452. * @return {(Function)} throttled fn.
  21453. */
  21454. function throttle(fn, delay, debounce) {
  21455. var currCall;
  21456. var lastCall = 0;
  21457. var lastExec = 0;
  21458. var timer = null;
  21459. var diff;
  21460. var scope;
  21461. var args;
  21462. var debounceNextCall;
  21463. delay = delay || 0;
  21464. function exec() {
  21465. lastExec = (new Date()).getTime();
  21466. timer = null;
  21467. fn.apply(scope, args || []);
  21468. }
  21469. var cb = function () {
  21470. currCall = (new Date()).getTime();
  21471. scope = this;
  21472. args = arguments;
  21473. var thisDelay = debounceNextCall || delay;
  21474. var thisDebounce = debounceNextCall || debounce;
  21475. debounceNextCall = null;
  21476. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  21477. clearTimeout(timer);
  21478. // Here we should make sure that: the `exec` SHOULD NOT be called later
  21479. // than a new call of `cb`, that is, preserving the command order. Consider
  21480. // calculating "scale rate" when roaming as an example. When a call of `cb`
  21481. // happens, either the `exec` is called dierectly, or the call is delayed.
  21482. // But the delayed call should never be later than next call of `cb`. Under
  21483. // this assurance, we can simply update view state each time `dispatchAction`
  21484. // triggered by user roaming, but not need to add extra code to avoid the
  21485. // state being "rolled-back".
  21486. if (thisDebounce) {
  21487. timer = setTimeout(exec, thisDelay);
  21488. }
  21489. else {
  21490. if (diff >= 0) {
  21491. exec();
  21492. }
  21493. else {
  21494. timer = setTimeout(exec, -diff);
  21495. }
  21496. }
  21497. lastCall = currCall;
  21498. };
  21499. /**
  21500. * Clear throttle.
  21501. * @public
  21502. */
  21503. cb.clear = function () {
  21504. if (timer) {
  21505. clearTimeout(timer);
  21506. timer = null;
  21507. }
  21508. };
  21509. /**
  21510. * Enable debounce once.
  21511. */
  21512. cb.debounceNextCall = function (debounceDelay) {
  21513. debounceNextCall = debounceDelay;
  21514. };
  21515. return cb;
  21516. }
  21517. /**
  21518. * Create throttle method or update throttle rate.
  21519. *
  21520. * @example
  21521. * ComponentView.prototype.render = function () {
  21522. * ...
  21523. * throttle.createOrUpdate(
  21524. * this,
  21525. * '_dispatchAction',
  21526. * this.model.get('throttle'),
  21527. * 'fixRate'
  21528. * );
  21529. * };
  21530. * ComponentView.prototype.remove = function () {
  21531. * throttle.clear(this, '_dispatchAction');
  21532. * };
  21533. * ComponentView.prototype.dispose = function () {
  21534. * throttle.clear(this, '_dispatchAction');
  21535. * };
  21536. *
  21537. * @public
  21538. * @param {Object} obj
  21539. * @param {string} fnAttr
  21540. * @param {number} [rate]
  21541. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  21542. * @return {Function} throttled function.
  21543. */
  21544. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  21545. var fn = obj[fnAttr];
  21546. if (!fn) {
  21547. return;
  21548. }
  21549. var originFn = fn[ORIGIN_METHOD] || fn;
  21550. var lastThrottleType = fn[THROTTLE_TYPE];
  21551. var lastRate = fn[RATE];
  21552. if (lastRate !== rate || lastThrottleType !== throttleType) {
  21553. if (rate == null || !throttleType) {
  21554. return (obj[fnAttr] = originFn);
  21555. }
  21556. fn = obj[fnAttr] = throttle(
  21557. originFn, rate, throttleType === 'debounce'
  21558. );
  21559. fn[ORIGIN_METHOD] = originFn;
  21560. fn[THROTTLE_TYPE] = throttleType;
  21561. fn[RATE] = rate;
  21562. }
  21563. return fn;
  21564. }
  21565. /**
  21566. * Clear throttle. Example see throttle.createOrUpdate.
  21567. *
  21568. * @public
  21569. * @param {Object} obj
  21570. * @param {string} fnAttr
  21571. */
  21572. function clear(obj, fnAttr) {
  21573. var fn = obj[fnAttr];
  21574. if (fn && fn[ORIGIN_METHOD]) {
  21575. obj[fnAttr] = fn[ORIGIN_METHOD];
  21576. }
  21577. }
  21578. /*
  21579. * Licensed to the Apache Software Foundation (ASF) under one
  21580. * or more contributor license agreements. See the NOTICE file
  21581. * distributed with this work for additional information
  21582. * regarding copyright ownership. The ASF licenses this file
  21583. * to you under the Apache License, Version 2.0 (the
  21584. * "License"); you may not use this file except in compliance
  21585. * with the License. You may obtain a copy of the License at
  21586. *
  21587. * http://www.apache.org/licenses/LICENSE-2.0
  21588. *
  21589. * Unless required by applicable law or agreed to in writing,
  21590. * software distributed under the License is distributed on an
  21591. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21592. * KIND, either express or implied. See the License for the
  21593. * specific language governing permissions and limitations
  21594. * under the License.
  21595. */
  21596. var seriesColor = {
  21597. createOnAllSeries: true,
  21598. performRawSeries: true,
  21599. reset: function (seriesModel, ecModel) {
  21600. var data = seriesModel.getData();
  21601. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  21602. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  21603. || seriesModel.getColorFromPalette(
  21604. // TODO series count changed.
  21605. seriesModel.name, null, ecModel.getSeriesCount()
  21606. ); // Default color
  21607. // FIXME Set color function or use the platte color
  21608. data.setVisual('color', color);
  21609. // Only visible series has each data be visual encoded
  21610. if (!ecModel.isSeriesFiltered(seriesModel)) {
  21611. if (typeof color === 'function' && !(color instanceof Gradient)) {
  21612. data.each(function (idx) {
  21613. data.setItemVisual(
  21614. idx, 'color', color(seriesModel.getDataParams(idx))
  21615. );
  21616. });
  21617. }
  21618. // itemStyle in each data item
  21619. var dataEach = function (data, idx) {
  21620. var itemModel = data.getItemModel(idx);
  21621. var color = itemModel.get(colorAccessPath, true);
  21622. if (color != null) {
  21623. data.setItemVisual(idx, 'color', color);
  21624. }
  21625. };
  21626. return { dataEach: data.hasItemOption ? dataEach : null };
  21627. }
  21628. }
  21629. };
  21630. /*
  21631. * Licensed to the Apache Software Foundation (ASF) under one
  21632. * or more contributor license agreements. See the NOTICE file
  21633. * distributed with this work for additional information
  21634. * regarding copyright ownership. The ASF licenses this file
  21635. * to you under the Apache License, Version 2.0 (the
  21636. * "License"); you may not use this file except in compliance
  21637. * with the License. You may obtain a copy of the License at
  21638. *
  21639. * http://www.apache.org/licenses/LICENSE-2.0
  21640. *
  21641. * Unless required by applicable law or agreed to in writing,
  21642. * software distributed under the License is distributed on an
  21643. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21644. * KIND, either express or implied. See the License for the
  21645. * specific language governing permissions and limitations
  21646. * under the License.
  21647. */
  21648. var lang = {
  21649. toolbox: {
  21650. brush: {
  21651. title: {
  21652. rect: 'Box Select',
  21653. polygon: 'Lasso Select',
  21654. lineX: 'Horizontally Select',
  21655. lineY: 'Vertically Select',
  21656. keep: 'Keep Selections',
  21657. clear: 'Clear Selections'
  21658. }
  21659. },
  21660. dataView: {
  21661. title: 'Data View',
  21662. lang: ['Data View', 'Close', 'Refresh']
  21663. },
  21664. dataZoom: {
  21665. title: {
  21666. zoom: 'Zoom',
  21667. back: 'Zoom Reset'
  21668. }
  21669. },
  21670. magicType: {
  21671. title: {
  21672. line: 'Switch to Line Chart',
  21673. bar: 'Switch to Bar Chart',
  21674. stack: 'Stack',
  21675. tiled: 'Tile'
  21676. }
  21677. },
  21678. restore: {
  21679. title: 'Restore'
  21680. },
  21681. saveAsImage: {
  21682. title: 'Save as Image',
  21683. lang: ['Right Click to Save Image']
  21684. }
  21685. }
  21686. };
  21687. /*
  21688. * Licensed to the Apache Software Foundation (ASF) under one
  21689. * or more contributor license agreements. See the NOTICE file
  21690. * distributed with this work for additional information
  21691. * regarding copyright ownership. The ASF licenses this file
  21692. * to you under the Apache License, Version 2.0 (the
  21693. * "License"); you may not use this file except in compliance
  21694. * with the License. You may obtain a copy of the License at
  21695. *
  21696. * http://www.apache.org/licenses/LICENSE-2.0
  21697. *
  21698. * Unless required by applicable law or agreed to in writing,
  21699. * software distributed under the License is distributed on an
  21700. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21701. * KIND, either express or implied. See the License for the
  21702. * specific language governing permissions and limitations
  21703. * under the License.
  21704. */
  21705. var aria = function (dom, ecModel) {
  21706. var ariaModel = ecModel.getModel('aria');
  21707. if (!ariaModel.get('show')) {
  21708. return;
  21709. }
  21710. else if (ariaModel.get('description')) {
  21711. dom.setAttribute('aria-label', ariaModel.get('description'));
  21712. return;
  21713. }
  21714. var seriesCnt = 0;
  21715. ecModel.eachSeries(function (seriesModel, idx) {
  21716. ++seriesCnt;
  21717. }, this);
  21718. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  21719. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  21720. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  21721. var ariaLabel;
  21722. if (seriesCnt < 1) {
  21723. // No series, no aria label
  21724. return;
  21725. }
  21726. else {
  21727. var title = getTitle();
  21728. if (title) {
  21729. ariaLabel = replace(getConfig('general.withTitle'), {
  21730. title: title
  21731. });
  21732. }
  21733. else {
  21734. ariaLabel = getConfig('general.withoutTitle');
  21735. }
  21736. var seriesLabels = [];
  21737. var prefix = seriesCnt > 1
  21738. ? 'series.multiple.prefix'
  21739. : 'series.single.prefix';
  21740. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  21741. ecModel.eachSeries(function (seriesModel, idx) {
  21742. if (idx < displaySeriesCnt) {
  21743. var seriesLabel;
  21744. var seriesName = seriesModel.get('name');
  21745. var seriesTpl = 'series.'
  21746. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  21747. seriesLabel = getConfig(seriesName
  21748. ? seriesTpl + 'withName'
  21749. : seriesTpl + 'withoutName');
  21750. seriesLabel = replace(seriesLabel, {
  21751. seriesId: seriesModel.seriesIndex,
  21752. seriesName: seriesModel.get('name'),
  21753. seriesType: getSeriesTypeName(seriesModel.subType)
  21754. });
  21755. var data = seriesModel.getData();
  21756. window.data = data;
  21757. if (data.count() > maxDataCnt) {
  21758. // Show part of data
  21759. seriesLabel += replace(getConfig('data.partialData'), {
  21760. displayCnt: maxDataCnt
  21761. });
  21762. }
  21763. else {
  21764. seriesLabel += getConfig('data.allData');
  21765. }
  21766. var dataLabels = [];
  21767. for (var i = 0; i < data.count(); i++) {
  21768. if (i < maxDataCnt) {
  21769. var name = data.getName(i);
  21770. var value = retrieveRawValue(data, i);
  21771. dataLabels.push(
  21772. replace(
  21773. name
  21774. ? getConfig('data.withName')
  21775. : getConfig('data.withoutName'),
  21776. {
  21777. name: name,
  21778. value: value
  21779. }
  21780. )
  21781. );
  21782. }
  21783. }
  21784. seriesLabel += dataLabels
  21785. .join(getConfig('data.separator.middle'))
  21786. + getConfig('data.separator.end');
  21787. seriesLabels.push(seriesLabel);
  21788. }
  21789. });
  21790. ariaLabel += seriesLabels
  21791. .join(getConfig('series.multiple.separator.middle'))
  21792. + getConfig('series.multiple.separator.end');
  21793. dom.setAttribute('aria-label', ariaLabel);
  21794. }
  21795. function replace(str, keyValues) {
  21796. if (typeof str !== 'string') {
  21797. return str;
  21798. }
  21799. var result = str;
  21800. each$1(keyValues, function (value, key) {
  21801. result = result.replace(
  21802. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  21803. value
  21804. );
  21805. });
  21806. return result;
  21807. }
  21808. function getConfig(path) {
  21809. var userConfig = ariaModel.get(path);
  21810. if (userConfig == null) {
  21811. var pathArr = path.split('.');
  21812. var result = lang.aria;
  21813. for (var i = 0; i < pathArr.length; ++i) {
  21814. result = result[pathArr[i]];
  21815. }
  21816. return result;
  21817. }
  21818. else {
  21819. return userConfig;
  21820. }
  21821. }
  21822. function getTitle() {
  21823. var title = ecModel.getModel('title').option;
  21824. if (title && title.length) {
  21825. title = title[0];
  21826. }
  21827. return title && title.text;
  21828. }
  21829. function getSeriesTypeName(type) {
  21830. return lang.series.typeNames[type] || '自定义图';
  21831. }
  21832. };
  21833. /*
  21834. * Licensed to the Apache Software Foundation (ASF) under one
  21835. * or more contributor license agreements. See the NOTICE file
  21836. * distributed with this work for additional information
  21837. * regarding copyright ownership. The ASF licenses this file
  21838. * to you under the Apache License, Version 2.0 (the
  21839. * "License"); you may not use this file except in compliance
  21840. * with the License. You may obtain a copy of the License at
  21841. *
  21842. * http://www.apache.org/licenses/LICENSE-2.0
  21843. *
  21844. * Unless required by applicable law or agreed to in writing,
  21845. * software distributed under the License is distributed on an
  21846. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21847. * KIND, either express or implied. See the License for the
  21848. * specific language governing permissions and limitations
  21849. * under the License.
  21850. */
  21851. var PI$1 = Math.PI;
  21852. /**
  21853. * @param {module:echarts/ExtensionAPI} api
  21854. * @param {Object} [opts]
  21855. * @param {string} [opts.text]
  21856. * @param {string} [opts.color]
  21857. * @param {string} [opts.textColor]
  21858. * @return {module:zrender/Element}
  21859. */
  21860. var loadingDefault = function (api, opts) {
  21861. opts = opts || {};
  21862. defaults(opts, {
  21863. text: 'loading',
  21864. color: '#c23531',
  21865. textColor: '#000',
  21866. maskColor: 'rgba(255, 255, 255, 0.8)',
  21867. zlevel: 0
  21868. });
  21869. var mask = new Rect({
  21870. style: {
  21871. fill: opts.maskColor
  21872. },
  21873. zlevel: opts.zlevel,
  21874. z: 10000
  21875. });
  21876. var arc = new Arc({
  21877. shape: {
  21878. startAngle: -PI$1 / 2,
  21879. endAngle: -PI$1 / 2 + 0.1,
  21880. r: 10
  21881. },
  21882. style: {
  21883. stroke: opts.color,
  21884. lineCap: 'round',
  21885. lineWidth: 5
  21886. },
  21887. zlevel: opts.zlevel,
  21888. z: 10001
  21889. });
  21890. var labelRect = new Rect({
  21891. style: {
  21892. fill: 'none',
  21893. text: opts.text,
  21894. textPosition: 'right',
  21895. textDistance: 10,
  21896. textFill: opts.textColor
  21897. },
  21898. zlevel: opts.zlevel,
  21899. z: 10001
  21900. });
  21901. arc.animateShape(true)
  21902. .when(1000, {
  21903. endAngle: PI$1 * 3 / 2
  21904. })
  21905. .start('circularInOut');
  21906. arc.animateShape(true)
  21907. .when(1000, {
  21908. startAngle: PI$1 * 3 / 2
  21909. })
  21910. .delay(300)
  21911. .start('circularInOut');
  21912. var group = new Group();
  21913. group.add(arc);
  21914. group.add(labelRect);
  21915. group.add(mask);
  21916. // Inject resize
  21917. group.resize = function () {
  21918. var cx = api.getWidth() / 2;
  21919. var cy = api.getHeight() / 2;
  21920. arc.setShape({
  21921. cx: cx,
  21922. cy: cy
  21923. });
  21924. var r = arc.shape.r;
  21925. labelRect.setShape({
  21926. x: cx - r,
  21927. y: cy - r,
  21928. width: r * 2,
  21929. height: r * 2
  21930. });
  21931. mask.setShape({
  21932. x: 0,
  21933. y: 0,
  21934. width: api.getWidth(),
  21935. height: api.getHeight()
  21936. });
  21937. };
  21938. group.resize();
  21939. return group;
  21940. };
  21941. /*
  21942. * Licensed to the Apache Software Foundation (ASF) under one
  21943. * or more contributor license agreements. See the NOTICE file
  21944. * distributed with this work for additional information
  21945. * regarding copyright ownership. The ASF licenses this file
  21946. * to you under the Apache License, Version 2.0 (the
  21947. * "License"); you may not use this file except in compliance
  21948. * with the License. You may obtain a copy of the License at
  21949. *
  21950. * http://www.apache.org/licenses/LICENSE-2.0
  21951. *
  21952. * Unless required by applicable law or agreed to in writing,
  21953. * software distributed under the License is distributed on an
  21954. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21955. * KIND, either express or implied. See the License for the
  21956. * specific language governing permissions and limitations
  21957. * under the License.
  21958. */
  21959. /**
  21960. * @module echarts/stream/Scheduler
  21961. */
  21962. /**
  21963. * @constructor
  21964. */
  21965. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21966. this.ecInstance = ecInstance;
  21967. this.api = api;
  21968. this.unfinished;
  21969. // Fix current processors in case that in some rear cases that
  21970. // processors might be registered after echarts instance created.
  21971. // Register processors incrementally for a echarts instance is
  21972. // not supported by this stream architecture.
  21973. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21974. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  21975. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21976. /**
  21977. * @private
  21978. * @type {
  21979. * [handlerUID: string]: {
  21980. * seriesTaskMap?: {
  21981. * [seriesUID: string]: Task
  21982. * },
  21983. * overallTask?: Task
  21984. * }
  21985. * }
  21986. */
  21987. this._stageTaskMap = createHashMap();
  21988. }
  21989. var proto = Scheduler.prototype;
  21990. /**
  21991. * @param {module:echarts/model/Global} ecModel
  21992. * @param {Object} payload
  21993. */
  21994. proto.restoreData = function (ecModel, payload) {
  21995. // TODO: Only restroe needed series and components, but not all components.
  21996. // Currently `restoreData` of all of the series and component will be called.
  21997. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21998. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21999. // and some components like coordinate system, axes, dataZoom, visualMap only
  22000. // need their target series refresh.
  22001. // (1) If we are implementing this feature some day, we should consider these cases:
  22002. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22003. // on the settings of `dataZoom`), it should be re-performed if the component
  22004. // is modified by `setOption`.
  22005. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22006. // it should be re-performed when the result array of `getTargetSeries` changed.
  22007. // We use `dependencies` to cover these issues.
  22008. // (3) How to update target series when coordinate system related components modified.
  22009. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22010. // and this case all of the tasks will be set as dirty.
  22011. ecModel.restoreData(payload);
  22012. // Theoretically an overall task not only depends on each of its target series, but also
  22013. // depends on all of the series.
  22014. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22015. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22016. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22017. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22018. // probably cause state chaos (consider `dataZoomProcessor`).
  22019. this._stageTaskMap.each(function (taskRecord) {
  22020. var overallTask = taskRecord.overallTask;
  22021. overallTask && overallTask.dirty();
  22022. });
  22023. };
  22024. // If seriesModel provided, incremental threshold is check by series data.
  22025. proto.getPerformArgs = function (task, isBlock) {
  22026. // For overall task
  22027. if (!task.__pipeline) {
  22028. return;
  22029. }
  22030. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22031. var pCtx = pipeline.context;
  22032. var incremental = !isBlock
  22033. && pipeline.progressiveEnabled
  22034. && (!pCtx || pCtx.progressiveRender)
  22035. && task.__idxInPipeline > pipeline.blockIndex;
  22036. var step = incremental ? pipeline.step : null;
  22037. var modDataCount = pCtx && pCtx.modDataCount;
  22038. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22039. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22040. };
  22041. proto.getPipeline = function (pipelineId) {
  22042. return this._pipelineMap.get(pipelineId);
  22043. };
  22044. /**
  22045. * Current, progressive rendering starts from visual and layout.
  22046. * Always detect render mode in the same stage, avoiding that incorrect
  22047. * detection caused by data filtering.
  22048. * Caution:
  22049. * `updateStreamModes` use `seriesModel.getData()`.
  22050. */
  22051. proto.updateStreamModes = function (seriesModel, view) {
  22052. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22053. var data = seriesModel.getData();
  22054. var dataLen = data.count();
  22055. // `progressiveRender` means that can render progressively in each
  22056. // animation frame. Note that some types of series do not provide
  22057. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22058. // use the term `incremental` but not `progressive` to describe the
  22059. // case that `chart.appendData`.
  22060. var progressiveRender = pipeline.progressiveEnabled
  22061. && view.incrementalPrepareRender
  22062. && dataLen >= pipeline.threshold;
  22063. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22064. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22065. // see `test/candlestick-large3.html`
  22066. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22067. seriesModel.pipelineContext = pipeline.context = {
  22068. progressiveRender: progressiveRender,
  22069. modDataCount: modDataCount,
  22070. large: large
  22071. };
  22072. };
  22073. proto.restorePipelines = function (ecModel) {
  22074. var scheduler = this;
  22075. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22076. ecModel.eachSeries(function (seriesModel) {
  22077. var progressive = seriesModel.getProgressive();
  22078. var pipelineId = seriesModel.uid;
  22079. pipelineMap.set(pipelineId, {
  22080. id: pipelineId,
  22081. head: null,
  22082. tail: null,
  22083. threshold: seriesModel.getProgressiveThreshold(),
  22084. progressiveEnabled: progressive
  22085. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22086. blockIndex: -1,
  22087. step: Math.round(progressive || 700),
  22088. count: 0
  22089. });
  22090. pipe(scheduler, seriesModel, seriesModel.dataTask);
  22091. });
  22092. };
  22093. proto.prepareStageTasks = function () {
  22094. var stageTaskMap = this._stageTaskMap;
  22095. var ecModel = this.ecInstance.getModel();
  22096. var api = this.api;
  22097. each$1(this._allHandlers, function (handler) {
  22098. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  22099. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  22100. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  22101. }, this);
  22102. };
  22103. proto.prepareView = function (view, model, ecModel, api) {
  22104. var renderTask = view.renderTask;
  22105. var context = renderTask.context;
  22106. context.model = model;
  22107. context.ecModel = ecModel;
  22108. context.api = api;
  22109. renderTask.__block = !view.incrementalPrepareRender;
  22110. pipe(this, model, renderTask);
  22111. };
  22112. proto.performDataProcessorTasks = function (ecModel, payload) {
  22113. // If we do not use `block` here, it should be considered when to update modes.
  22114. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  22115. };
  22116. // opt
  22117. // opt.visualType: 'visual' or 'layout'
  22118. // opt.setDirty
  22119. proto.performVisualTasks = function (ecModel, payload, opt) {
  22120. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  22121. };
  22122. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  22123. opt = opt || {};
  22124. var unfinished;
  22125. each$1(stageHandlers, function (stageHandler, idx) {
  22126. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22127. return;
  22128. }
  22129. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22130. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22131. var overallTask = stageHandlerRecord.overallTask;
  22132. if (overallTask) {
  22133. var overallNeedDirty;
  22134. var agentStubMap = overallTask.agentStubMap;
  22135. agentStubMap.each(function (stub) {
  22136. if (needSetDirty(opt, stub)) {
  22137. stub.dirty();
  22138. overallNeedDirty = true;
  22139. }
  22140. });
  22141. overallNeedDirty && overallTask.dirty();
  22142. updatePayload(overallTask, payload);
  22143. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  22144. // Execute stubs firstly, which may set the overall task dirty,
  22145. // then execute the overall task. And stub will call seriesModel.setData,
  22146. // which ensures that in the overallTask seriesModel.getData() will not
  22147. // return incorrect data.
  22148. agentStubMap.each(function (stub) {
  22149. stub.perform(performArgs);
  22150. });
  22151. unfinished |= overallTask.perform(performArgs);
  22152. }
  22153. else if (seriesTaskMap) {
  22154. seriesTaskMap.each(function (task, pipelineId) {
  22155. if (needSetDirty(opt, task)) {
  22156. task.dirty();
  22157. }
  22158. var performArgs = scheduler.getPerformArgs(task, opt.block);
  22159. performArgs.skip = !stageHandler.performRawSeries
  22160. && ecModel.isSeriesFiltered(task.context.model);
  22161. updatePayload(task, payload);
  22162. unfinished |= task.perform(performArgs);
  22163. });
  22164. }
  22165. });
  22166. function needSetDirty(opt, task) {
  22167. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22168. }
  22169. scheduler.unfinished |= unfinished;
  22170. }
  22171. proto.performSeriesTasks = function (ecModel) {
  22172. var unfinished;
  22173. ecModel.eachSeries(function (seriesModel) {
  22174. // Progress to the end for dataInit and dataRestore.
  22175. unfinished |= seriesModel.dataTask.perform();
  22176. });
  22177. this.unfinished |= unfinished;
  22178. };
  22179. proto.plan = function () {
  22180. // Travel pipelines, check block.
  22181. this._pipelineMap.each(function (pipeline) {
  22182. var task = pipeline.tail;
  22183. do {
  22184. if (task.__block) {
  22185. pipeline.blockIndex = task.__idxInPipeline;
  22186. break;
  22187. }
  22188. task = task.getUpstream();
  22189. }
  22190. while (task);
  22191. });
  22192. };
  22193. var updatePayload = proto.updatePayload = function (task, payload) {
  22194. payload !== 'remain' && (task.context.payload = payload);
  22195. };
  22196. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22197. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  22198. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  22199. var seriesType = stageHandler.seriesType;
  22200. var getTargetSeries = stageHandler.getTargetSeries;
  22201. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  22202. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  22203. // it works but it may cause other irrelevant charts blocked.
  22204. if (stageHandler.createOnAllSeries) {
  22205. ecModel.eachRawSeries(create);
  22206. }
  22207. else if (seriesType) {
  22208. ecModel.eachRawSeriesByType(seriesType, create);
  22209. }
  22210. else if (getTargetSeries) {
  22211. getTargetSeries(ecModel, api).each(create);
  22212. }
  22213. function create(seriesModel) {
  22214. var pipelineId = seriesModel.uid;
  22215. // Init tasks for each seriesModel only once.
  22216. // Reuse original task instance.
  22217. var task = seriesTaskMap.get(pipelineId)
  22218. || seriesTaskMap.set(pipelineId, createTask({
  22219. plan: seriesTaskPlan,
  22220. reset: seriesTaskReset,
  22221. count: seriesTaskCount
  22222. }));
  22223. task.context = {
  22224. model: seriesModel,
  22225. ecModel: ecModel,
  22226. api: api,
  22227. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  22228. plan: stageHandler.plan,
  22229. reset: stageHandler.reset,
  22230. scheduler: scheduler
  22231. };
  22232. pipe(scheduler, seriesModel, task);
  22233. }
  22234. // Clear unused series tasks.
  22235. var pipelineMap = scheduler._pipelineMap;
  22236. seriesTaskMap.each(function (task, pipelineId) {
  22237. if (!pipelineMap.get(pipelineId)) {
  22238. task.dispose();
  22239. seriesTaskMap.removeKey(pipelineId);
  22240. }
  22241. });
  22242. }
  22243. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22244. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  22245. // For overall task, the function only be called on reset stage.
  22246. || createTask({reset: overallTaskReset});
  22247. overallTask.context = {
  22248. ecModel: ecModel,
  22249. api: api,
  22250. overallReset: stageHandler.overallReset,
  22251. scheduler: scheduler
  22252. };
  22253. // Reuse orignal stubs.
  22254. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  22255. var seriesType = stageHandler.seriesType;
  22256. var getTargetSeries = stageHandler.getTargetSeries;
  22257. var overallProgress = true;
  22258. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  22259. // An overall task with seriesType detected or has `getTargetSeries`, we add
  22260. // stub in each pipelines, it will set the overall task dirty when the pipeline
  22261. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  22262. // we set the pipeline block.
  22263. if (seriesType) {
  22264. ecModel.eachRawSeriesByType(seriesType, createStub);
  22265. }
  22266. else if (getTargetSeries) {
  22267. getTargetSeries(ecModel, api).each(createStub);
  22268. }
  22269. // Otherwise, (usually it is legancy case), the overall task will only be
  22270. // executed when upstream dirty. Otherwise the progressive rendering of all
  22271. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  22272. // dirty info from upsteam.
  22273. else {
  22274. overallProgress = false;
  22275. each$1(ecModel.getSeries(), createStub);
  22276. }
  22277. function createStub(seriesModel) {
  22278. var pipelineId = seriesModel.uid;
  22279. var stub = agentStubMap.get(pipelineId);
  22280. if (!stub) {
  22281. stub = agentStubMap.set(pipelineId, createTask(
  22282. {reset: stubReset, onDirty: stubOnDirty}
  22283. ));
  22284. // When the result of `getTargetSeries` changed, the overallTask
  22285. // should be set as dirty and re-performed.
  22286. overallTask.dirty();
  22287. }
  22288. stub.context = {
  22289. model: seriesModel,
  22290. overallProgress: overallProgress,
  22291. modifyOutputEnd: modifyOutputEnd
  22292. };
  22293. stub.agent = overallTask;
  22294. stub.__block = overallProgress;
  22295. pipe(scheduler, seriesModel, stub);
  22296. }
  22297. // Clear unused stubs.
  22298. var pipelineMap = scheduler._pipelineMap;
  22299. agentStubMap.each(function (stub, pipelineId) {
  22300. if (!pipelineMap.get(pipelineId)) {
  22301. stub.dispose();
  22302. // When the result of `getTargetSeries` changed, the overallTask
  22303. // should be set as dirty and re-performed.
  22304. overallTask.dirty();
  22305. agentStubMap.removeKey(pipelineId);
  22306. }
  22307. });
  22308. }
  22309. function overallTaskReset(context) {
  22310. context.overallReset(
  22311. context.ecModel, context.api, context.payload
  22312. );
  22313. }
  22314. function stubReset(context, upstreamContext) {
  22315. return context.overallProgress && stubProgress;
  22316. }
  22317. function stubProgress() {
  22318. this.agent.dirty();
  22319. this.getDownstream().dirty();
  22320. }
  22321. function stubOnDirty() {
  22322. this.agent && this.agent.dirty();
  22323. }
  22324. function seriesTaskPlan(context) {
  22325. return context.plan && context.plan(
  22326. context.model, context.ecModel, context.api, context.payload
  22327. );
  22328. }
  22329. function seriesTaskReset(context) {
  22330. if (context.useClearVisual) {
  22331. context.data.clearAllVisual();
  22332. }
  22333. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  22334. context.model, context.ecModel, context.api, context.payload
  22335. ));
  22336. return resetDefines.length > 1
  22337. ? map(resetDefines, function (v, idx) {
  22338. return makeSeriesTaskProgress(idx);
  22339. })
  22340. : singleSeriesTaskProgress;
  22341. }
  22342. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  22343. function makeSeriesTaskProgress(resetDefineIdx) {
  22344. return function (params, context) {
  22345. var data = context.data;
  22346. var resetDefine = context.resetDefines[resetDefineIdx];
  22347. if (resetDefine && resetDefine.dataEach) {
  22348. for (var i = params.start; i < params.end; i++) {
  22349. resetDefine.dataEach(data, i);
  22350. }
  22351. }
  22352. else if (resetDefine && resetDefine.progress) {
  22353. resetDefine.progress(params, data);
  22354. }
  22355. };
  22356. }
  22357. function seriesTaskCount(context) {
  22358. return context.data.count();
  22359. }
  22360. function pipe(scheduler, seriesModel, task) {
  22361. var pipelineId = seriesModel.uid;
  22362. var pipeline = scheduler._pipelineMap.get(pipelineId);
  22363. !pipeline.head && (pipeline.head = task);
  22364. pipeline.tail && pipeline.tail.pipe(task);
  22365. pipeline.tail = task;
  22366. task.__idxInPipeline = pipeline.count++;
  22367. task.__pipeline = pipeline;
  22368. }
  22369. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  22370. if (isFunction$1(stageHandler)) {
  22371. stageHandler = {
  22372. overallReset: stageHandler,
  22373. seriesType: detectSeriseType(stageHandler)
  22374. };
  22375. }
  22376. stageHandler.uid = getUID('stageHandler');
  22377. visualType && (stageHandler.visualType = visualType);
  22378. return stageHandler;
  22379. };
  22380. /**
  22381. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  22382. * To ensure that they can work normally, they should work in block mode, that is,
  22383. * they should not be started util the previous tasks finished. So they cause the
  22384. * progressive rendering disabled. We try to detect the series type, to narrow down
  22385. * the block range to only the series type they concern, but not all series.
  22386. */
  22387. function detectSeriseType(legacyFunc) {
  22388. seriesType = null;
  22389. try {
  22390. // Assume there is no async when calling `eachSeriesByType`.
  22391. legacyFunc(ecModelMock, apiMock);
  22392. }
  22393. catch (e) {
  22394. }
  22395. return seriesType;
  22396. }
  22397. var ecModelMock = {};
  22398. var apiMock = {};
  22399. var seriesType;
  22400. mockMethods(ecModelMock, GlobalModel);
  22401. mockMethods(apiMock, ExtensionAPI);
  22402. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  22403. seriesType = type;
  22404. };
  22405. ecModelMock.eachComponent = function (cond) {
  22406. if (cond.mainType === 'series' && cond.subType) {
  22407. seriesType = cond.subType;
  22408. }
  22409. };
  22410. function mockMethods(target, Clz) {
  22411. /* eslint-disable */
  22412. for (var name in Clz.prototype) {
  22413. // Do not use hasOwnProperty
  22414. target[name] = noop;
  22415. }
  22416. /* eslint-enable */
  22417. }
  22418. /*
  22419. * Licensed to the Apache Software Foundation (ASF) under one
  22420. * or more contributor license agreements. See the NOTICE file
  22421. * distributed with this work for additional information
  22422. * regarding copyright ownership. The ASF licenses this file
  22423. * to you under the Apache License, Version 2.0 (the
  22424. * "License"); you may not use this file except in compliance
  22425. * with the License. You may obtain a copy of the License at
  22426. *
  22427. * http://www.apache.org/licenses/LICENSE-2.0
  22428. *
  22429. * Unless required by applicable law or agreed to in writing,
  22430. * software distributed under the License is distributed on an
  22431. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22432. * KIND, either express or implied. See the License for the
  22433. * specific language governing permissions and limitations
  22434. * under the License.
  22435. */
  22436. var colorAll = [
  22437. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  22438. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  22439. ];
  22440. var lightTheme = {
  22441. color: colorAll,
  22442. colorLayer: [
  22443. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  22444. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  22445. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  22446. colorAll
  22447. ]
  22448. };
  22449. /*
  22450. * Licensed to the Apache Software Foundation (ASF) under one
  22451. * or more contributor license agreements. See the NOTICE file
  22452. * distributed with this work for additional information
  22453. * regarding copyright ownership. The ASF licenses this file
  22454. * to you under the Apache License, Version 2.0 (the
  22455. * "License"); you may not use this file except in compliance
  22456. * with the License. You may obtain a copy of the License at
  22457. *
  22458. * http://www.apache.org/licenses/LICENSE-2.0
  22459. *
  22460. * Unless required by applicable law or agreed to in writing,
  22461. * software distributed under the License is distributed on an
  22462. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22463. * KIND, either express or implied. See the License for the
  22464. * specific language governing permissions and limitations
  22465. * under the License.
  22466. */
  22467. var contrastColor = '#eee';
  22468. var axisCommon = function () {
  22469. return {
  22470. axisLine: {
  22471. lineStyle: {
  22472. color: contrastColor
  22473. }
  22474. },
  22475. axisTick: {
  22476. lineStyle: {
  22477. color: contrastColor
  22478. }
  22479. },
  22480. axisLabel: {
  22481. textStyle: {
  22482. color: contrastColor
  22483. }
  22484. },
  22485. splitLine: {
  22486. lineStyle: {
  22487. type: 'dashed',
  22488. color: '#aaa'
  22489. }
  22490. },
  22491. splitArea: {
  22492. areaStyle: {
  22493. color: contrastColor
  22494. }
  22495. }
  22496. };
  22497. };
  22498. var colorPalette = [
  22499. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  22500. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  22501. ];
  22502. var theme = {
  22503. color: colorPalette,
  22504. backgroundColor: '#333',
  22505. tooltip: {
  22506. axisPointer: {
  22507. lineStyle: {
  22508. color: contrastColor
  22509. },
  22510. crossStyle: {
  22511. color: contrastColor
  22512. }
  22513. }
  22514. },
  22515. legend: {
  22516. textStyle: {
  22517. color: contrastColor
  22518. }
  22519. },
  22520. textStyle: {
  22521. color: contrastColor
  22522. },
  22523. title: {
  22524. textStyle: {
  22525. color: contrastColor
  22526. }
  22527. },
  22528. toolbox: {
  22529. iconStyle: {
  22530. normal: {
  22531. borderColor: contrastColor
  22532. }
  22533. }
  22534. },
  22535. dataZoom: {
  22536. textStyle: {
  22537. color: contrastColor
  22538. }
  22539. },
  22540. visualMap: {
  22541. textStyle: {
  22542. color: contrastColor
  22543. }
  22544. },
  22545. timeline: {
  22546. lineStyle: {
  22547. color: contrastColor
  22548. },
  22549. itemStyle: {
  22550. normal: {
  22551. color: colorPalette[1]
  22552. }
  22553. },
  22554. label: {
  22555. normal: {
  22556. textStyle: {
  22557. color: contrastColor
  22558. }
  22559. }
  22560. },
  22561. controlStyle: {
  22562. normal: {
  22563. color: contrastColor,
  22564. borderColor: contrastColor
  22565. }
  22566. }
  22567. },
  22568. timeAxis: axisCommon(),
  22569. logAxis: axisCommon(),
  22570. valueAxis: axisCommon(),
  22571. categoryAxis: axisCommon(),
  22572. line: {
  22573. symbol: 'circle'
  22574. },
  22575. graph: {
  22576. color: colorPalette
  22577. },
  22578. gauge: {
  22579. title: {
  22580. textStyle: {
  22581. color: contrastColor
  22582. }
  22583. }
  22584. },
  22585. candlestick: {
  22586. itemStyle: {
  22587. normal: {
  22588. color: '#FD1050',
  22589. color0: '#0CF49B',
  22590. borderColor: '#FD1050',
  22591. borderColor0: '#0CF49B'
  22592. }
  22593. }
  22594. }
  22595. };
  22596. theme.categoryAxis.splitLine.show = false;
  22597. /*
  22598. * Licensed to the Apache Software Foundation (ASF) under one
  22599. * or more contributor license agreements. See the NOTICE file
  22600. * distributed with this work for additional information
  22601. * regarding copyright ownership. The ASF licenses this file
  22602. * to you under the Apache License, Version 2.0 (the
  22603. * "License"); you may not use this file except in compliance
  22604. * with the License. You may obtain a copy of the License at
  22605. *
  22606. * http://www.apache.org/licenses/LICENSE-2.0
  22607. *
  22608. * Unless required by applicable law or agreed to in writing,
  22609. * software distributed under the License is distributed on an
  22610. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22611. * KIND, either express or implied. See the License for the
  22612. * specific language governing permissions and limitations
  22613. * under the License.
  22614. */
  22615. /**
  22616. * This module is imported by echarts directly.
  22617. *
  22618. * Notice:
  22619. * Always keep this file exists for backward compatibility.
  22620. * Because before 4.1.0, dataset is an optional component,
  22621. * some users may import this module manually.
  22622. */
  22623. ComponentModel.extend({
  22624. type: 'dataset',
  22625. /**
  22626. * @protected
  22627. */
  22628. defaultOption: {
  22629. // 'row', 'column'
  22630. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  22631. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  22632. sourceHeader: null,
  22633. dimensions: null,
  22634. source: null
  22635. },
  22636. optionUpdated: function () {
  22637. detectSourceFormat(this);
  22638. }
  22639. });
  22640. Component.extend({
  22641. type: 'dataset'
  22642. });
  22643. /**
  22644. * 椭圆形状
  22645. * @module zrender/graphic/shape/Ellipse
  22646. */
  22647. var Ellipse = Path.extend({
  22648. type: 'ellipse',
  22649. shape: {
  22650. cx: 0, cy: 0,
  22651. rx: 0, ry: 0
  22652. },
  22653. buildPath: function (ctx, shape) {
  22654. var k = 0.5522848;
  22655. var x = shape.cx;
  22656. var y = shape.cy;
  22657. var a = shape.rx;
  22658. var b = shape.ry;
  22659. var ox = a * k; // 水平控制点偏移量
  22660. var oy = b * k; // 垂直控制点偏移量
  22661. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  22662. ctx.moveTo(x - a, y);
  22663. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  22664. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  22665. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  22666. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  22667. ctx.closePath();
  22668. }
  22669. });
  22670. // import RadialGradient from '../graphic/RadialGradient';
  22671. // import Pattern from '../graphic/Pattern';
  22672. // import * as vector from '../core/vector';
  22673. // Most of the values can be separated by comma and/or white space.
  22674. var DILIMITER_REG = /[\s,]+/;
  22675. /**
  22676. * For big svg string, this method might be time consuming.
  22677. *
  22678. * @param {string} svg xml string
  22679. * @return {Object} xml root.
  22680. */
  22681. function parseXML(svg) {
  22682. if (isString(svg)) {
  22683. var parser = new DOMParser();
  22684. svg = parser.parseFromString(svg, 'text/xml');
  22685. }
  22686. // Document node. If using $.get, doc node may be input.
  22687. if (svg.nodeType === 9) {
  22688. svg = svg.firstChild;
  22689. }
  22690. // nodeName of <!DOCTYPE svg> is also 'svg'.
  22691. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  22692. svg = svg.nextSibling;
  22693. }
  22694. return svg;
  22695. }
  22696. function SVGParser() {
  22697. this._defs = {};
  22698. this._root = null;
  22699. this._isDefine = false;
  22700. this._isText = false;
  22701. }
  22702. SVGParser.prototype.parse = function (xml, opt) {
  22703. opt = opt || {};
  22704. var svg = parseXML(xml);
  22705. if (!svg) {
  22706. throw new Error('Illegal svg');
  22707. }
  22708. var root = new Group();
  22709. this._root = root;
  22710. // parse view port
  22711. var viewBox = svg.getAttribute('viewBox') || '';
  22712. // If width/height not specified, means "100%" of `opt.width/height`.
  22713. // TODO: Other percent value not supported yet.
  22714. var width = parseFloat(svg.getAttribute('width') || opt.width);
  22715. var height = parseFloat(svg.getAttribute('height') || opt.height);
  22716. // If width/height not specified, set as null for output.
  22717. isNaN(width) && (width = null);
  22718. isNaN(height) && (height = null);
  22719. // Apply inline style on svg element.
  22720. parseAttributes(svg, root, null, true);
  22721. var child = svg.firstChild;
  22722. while (child) {
  22723. this._parseNode(child, root);
  22724. child = child.nextSibling;
  22725. }
  22726. var viewBoxRect;
  22727. var viewBoxTransform;
  22728. if (viewBox) {
  22729. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  22730. // Some invalid case like viewBox: 'none'.
  22731. if (viewBoxArr.length >= 4) {
  22732. viewBoxRect = {
  22733. x: parseFloat(viewBoxArr[0] || 0),
  22734. y: parseFloat(viewBoxArr[1] || 0),
  22735. width: parseFloat(viewBoxArr[2]),
  22736. height: parseFloat(viewBoxArr[3])
  22737. };
  22738. }
  22739. }
  22740. if (viewBoxRect && width != null && height != null) {
  22741. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  22742. if (!opt.ignoreViewBox) {
  22743. // If set transform on the output group, it probably bring trouble when
  22744. // some users only intend to show the clipped content inside the viewBox,
  22745. // but not intend to transform the output group. So we keep the output
  22746. // group no transform. If the user intend to use the viewBox as a
  22747. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  22748. // manually according to the viewBox info in the output of this method.
  22749. var elRoot = root;
  22750. root = new Group();
  22751. root.add(elRoot);
  22752. elRoot.scale = viewBoxTransform.scale.slice();
  22753. elRoot.position = viewBoxTransform.position.slice();
  22754. }
  22755. }
  22756. // Some shapes might be overflow the viewport, which should be
  22757. // clipped despite whether the viewBox is used, as the SVG does.
  22758. if (!opt.ignoreRootClip && width != null && height != null) {
  22759. root.setClipPath(new Rect({
  22760. shape: {x: 0, y: 0, width: width, height: height}
  22761. }));
  22762. }
  22763. // Set width/height on group just for output the viewport size.
  22764. return {
  22765. root: root,
  22766. width: width,
  22767. height: height,
  22768. viewBoxRect: viewBoxRect,
  22769. viewBoxTransform: viewBoxTransform
  22770. };
  22771. };
  22772. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  22773. var nodeName = xmlNode.nodeName.toLowerCase();
  22774. // TODO
  22775. // support <style>...</style> in svg, where nodeName is 'style',
  22776. // CSS classes is defined globally wherever the style tags are declared.
  22777. if (nodeName === 'defs') {
  22778. // define flag
  22779. this._isDefine = true;
  22780. }
  22781. else if (nodeName === 'text') {
  22782. this._isText = true;
  22783. }
  22784. var el;
  22785. if (this._isDefine) {
  22786. var parser = defineParsers[nodeName];
  22787. if (parser) {
  22788. var def = parser.call(this, xmlNode);
  22789. var id = xmlNode.getAttribute('id');
  22790. if (id) {
  22791. this._defs[id] = def;
  22792. }
  22793. }
  22794. }
  22795. else {
  22796. var parser = nodeParsers[nodeName];
  22797. if (parser) {
  22798. el = parser.call(this, xmlNode, parentGroup);
  22799. parentGroup.add(el);
  22800. }
  22801. }
  22802. var child = xmlNode.firstChild;
  22803. while (child) {
  22804. if (child.nodeType === 1) {
  22805. this._parseNode(child, el);
  22806. }
  22807. // Is text
  22808. if (child.nodeType === 3 && this._isText) {
  22809. this._parseText(child, el);
  22810. }
  22811. child = child.nextSibling;
  22812. }
  22813. // Quit define
  22814. if (nodeName === 'defs') {
  22815. this._isDefine = false;
  22816. }
  22817. else if (nodeName === 'text') {
  22818. this._isText = false;
  22819. }
  22820. };
  22821. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  22822. if (xmlNode.nodeType === 1) {
  22823. var dx = xmlNode.getAttribute('dx') || 0;
  22824. var dy = xmlNode.getAttribute('dy') || 0;
  22825. this._textX += parseFloat(dx);
  22826. this._textY += parseFloat(dy);
  22827. }
  22828. var text = new Text({
  22829. style: {
  22830. text: xmlNode.textContent,
  22831. transformText: true
  22832. },
  22833. position: [this._textX || 0, this._textY || 0]
  22834. });
  22835. inheritStyle(parentGroup, text);
  22836. parseAttributes(xmlNode, text, this._defs);
  22837. var fontSize = text.style.fontSize;
  22838. if (fontSize && fontSize < 9) {
  22839. // PENDING
  22840. text.style.fontSize = 9;
  22841. text.scale = text.scale || [1, 1];
  22842. text.scale[0] *= fontSize / 9;
  22843. text.scale[1] *= fontSize / 9;
  22844. }
  22845. var rect = text.getBoundingRect();
  22846. this._textX += rect.width;
  22847. parentGroup.add(text);
  22848. return text;
  22849. };
  22850. var nodeParsers = {
  22851. 'g': function (xmlNode, parentGroup) {
  22852. var g = new Group();
  22853. inheritStyle(parentGroup, g);
  22854. parseAttributes(xmlNode, g, this._defs);
  22855. return g;
  22856. },
  22857. 'rect': function (xmlNode, parentGroup) {
  22858. var rect = new Rect();
  22859. inheritStyle(parentGroup, rect);
  22860. parseAttributes(xmlNode, rect, this._defs);
  22861. rect.setShape({
  22862. x: parseFloat(xmlNode.getAttribute('x') || 0),
  22863. y: parseFloat(xmlNode.getAttribute('y') || 0),
  22864. width: parseFloat(xmlNode.getAttribute('width') || 0),
  22865. height: parseFloat(xmlNode.getAttribute('height') || 0)
  22866. });
  22867. // console.log(xmlNode.getAttribute('transform'));
  22868. // console.log(rect.transform);
  22869. return rect;
  22870. },
  22871. 'circle': function (xmlNode, parentGroup) {
  22872. var circle = new Circle();
  22873. inheritStyle(parentGroup, circle);
  22874. parseAttributes(xmlNode, circle, this._defs);
  22875. circle.setShape({
  22876. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  22877. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  22878. r: parseFloat(xmlNode.getAttribute('r') || 0)
  22879. });
  22880. return circle;
  22881. },
  22882. 'line': function (xmlNode, parentGroup) {
  22883. var line = new Line();
  22884. inheritStyle(parentGroup, line);
  22885. parseAttributes(xmlNode, line, this._defs);
  22886. line.setShape({
  22887. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  22888. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  22889. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  22890. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  22891. });
  22892. return line;
  22893. },
  22894. 'ellipse': function (xmlNode, parentGroup) {
  22895. var ellipse = new Ellipse();
  22896. inheritStyle(parentGroup, ellipse);
  22897. parseAttributes(xmlNode, ellipse, this._defs);
  22898. ellipse.setShape({
  22899. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  22900. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  22901. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  22902. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  22903. });
  22904. return ellipse;
  22905. },
  22906. 'polygon': function (xmlNode, parentGroup) {
  22907. var points = xmlNode.getAttribute('points');
  22908. if (points) {
  22909. points = parsePoints(points);
  22910. }
  22911. var polygon = new Polygon({
  22912. shape: {
  22913. points: points || []
  22914. }
  22915. });
  22916. inheritStyle(parentGroup, polygon);
  22917. parseAttributes(xmlNode, polygon, this._defs);
  22918. return polygon;
  22919. },
  22920. 'polyline': function (xmlNode, parentGroup) {
  22921. var path = new Path();
  22922. inheritStyle(parentGroup, path);
  22923. parseAttributes(xmlNode, path, this._defs);
  22924. var points = xmlNode.getAttribute('points');
  22925. if (points) {
  22926. points = parsePoints(points);
  22927. }
  22928. var polyline = new Polyline({
  22929. shape: {
  22930. points: points || []
  22931. }
  22932. });
  22933. return polyline;
  22934. },
  22935. 'image': function (xmlNode, parentGroup) {
  22936. var img = new ZImage();
  22937. inheritStyle(parentGroup, img);
  22938. parseAttributes(xmlNode, img, this._defs);
  22939. img.setStyle({
  22940. image: xmlNode.getAttribute('xlink:href'),
  22941. x: xmlNode.getAttribute('x'),
  22942. y: xmlNode.getAttribute('y'),
  22943. width: xmlNode.getAttribute('width'),
  22944. height: xmlNode.getAttribute('height')
  22945. });
  22946. return img;
  22947. },
  22948. 'text': function (xmlNode, parentGroup) {
  22949. var x = xmlNode.getAttribute('x') || 0;
  22950. var y = xmlNode.getAttribute('y') || 0;
  22951. var dx = xmlNode.getAttribute('dx') || 0;
  22952. var dy = xmlNode.getAttribute('dy') || 0;
  22953. this._textX = parseFloat(x) + parseFloat(dx);
  22954. this._textY = parseFloat(y) + parseFloat(dy);
  22955. var g = new Group();
  22956. inheritStyle(parentGroup, g);
  22957. parseAttributes(xmlNode, g, this._defs);
  22958. return g;
  22959. },
  22960. 'tspan': function (xmlNode, parentGroup) {
  22961. var x = xmlNode.getAttribute('x');
  22962. var y = xmlNode.getAttribute('y');
  22963. if (x != null) {
  22964. // new offset x
  22965. this._textX = parseFloat(x);
  22966. }
  22967. if (y != null) {
  22968. // new offset y
  22969. this._textY = parseFloat(y);
  22970. }
  22971. var dx = xmlNode.getAttribute('dx') || 0;
  22972. var dy = xmlNode.getAttribute('dy') || 0;
  22973. var g = new Group();
  22974. inheritStyle(parentGroup, g);
  22975. parseAttributes(xmlNode, g, this._defs);
  22976. this._textX += dx;
  22977. this._textY += dy;
  22978. return g;
  22979. },
  22980. 'path': function (xmlNode, parentGroup) {
  22981. // TODO svg fill rule
  22982. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  22983. // path.style.globalCompositeOperation = 'xor';
  22984. var d = xmlNode.getAttribute('d') || '';
  22985. // Performance sensitive.
  22986. var path = createFromString(d);
  22987. inheritStyle(parentGroup, path);
  22988. parseAttributes(xmlNode, path, this._defs);
  22989. return path;
  22990. }
  22991. };
  22992. var defineParsers = {
  22993. 'lineargradient': function (xmlNode) {
  22994. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  22995. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  22996. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  22997. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  22998. var gradient = new LinearGradient(x1, y1, x2, y2);
  22999. _parseGradientColorStops(xmlNode, gradient);
  23000. return gradient;
  23001. },
  23002. 'radialgradient': function (xmlNode) {
  23003. }
  23004. };
  23005. function _parseGradientColorStops(xmlNode, gradient) {
  23006. var stop = xmlNode.firstChild;
  23007. while (stop) {
  23008. if (stop.nodeType === 1) {
  23009. var offset = stop.getAttribute('offset');
  23010. if (offset.indexOf('%') > 0) { // percentage
  23011. offset = parseInt(offset, 10) / 100;
  23012. }
  23013. else if (offset) { // number from 0 to 1
  23014. offset = parseFloat(offset);
  23015. }
  23016. else {
  23017. offset = 0;
  23018. }
  23019. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23020. gradient.addColorStop(offset, stopColor);
  23021. }
  23022. stop = stop.nextSibling;
  23023. }
  23024. }
  23025. function inheritStyle(parent, child) {
  23026. if (parent && parent.__inheritedStyle) {
  23027. if (!child.__inheritedStyle) {
  23028. child.__inheritedStyle = {};
  23029. }
  23030. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23031. }
  23032. }
  23033. function parsePoints(pointsString) {
  23034. var list = trim(pointsString).split(DILIMITER_REG);
  23035. var points = [];
  23036. for (var i = 0; i < list.length; i += 2) {
  23037. var x = parseFloat(list[i]);
  23038. var y = parseFloat(list[i + 1]);
  23039. points.push([x, y]);
  23040. }
  23041. return points;
  23042. }
  23043. var attributesMap = {
  23044. 'fill': 'fill',
  23045. 'stroke': 'stroke',
  23046. 'stroke-width': 'lineWidth',
  23047. 'opacity': 'opacity',
  23048. 'fill-opacity': 'fillOpacity',
  23049. 'stroke-opacity': 'strokeOpacity',
  23050. 'stroke-dasharray': 'lineDash',
  23051. 'stroke-dashoffset': 'lineDashOffset',
  23052. 'stroke-linecap': 'lineCap',
  23053. 'stroke-linejoin': 'lineJoin',
  23054. 'stroke-miterlimit': 'miterLimit',
  23055. 'font-family': 'fontFamily',
  23056. 'font-size': 'fontSize',
  23057. 'font-style': 'fontStyle',
  23058. 'font-weight': 'fontWeight',
  23059. 'text-align': 'textAlign',
  23060. 'alignment-baseline': 'textBaseline'
  23061. };
  23062. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  23063. var zrStyle = el.__inheritedStyle || {};
  23064. var isTextEl = el.type === 'text';
  23065. // TODO Shadow
  23066. if (xmlNode.nodeType === 1) {
  23067. parseTransformAttribute(xmlNode, el);
  23068. extend(zrStyle, parseStyleAttribute(xmlNode));
  23069. if (!onlyInlineStyle) {
  23070. for (var svgAttrName in attributesMap) {
  23071. if (attributesMap.hasOwnProperty(svgAttrName)) {
  23072. var attrValue = xmlNode.getAttribute(svgAttrName);
  23073. if (attrValue != null) {
  23074. zrStyle[attributesMap[svgAttrName]] = attrValue;
  23075. }
  23076. }
  23077. }
  23078. }
  23079. }
  23080. var elFillProp = isTextEl ? 'textFill' : 'fill';
  23081. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  23082. el.style = el.style || new Style();
  23083. var elStyle = el.style;
  23084. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  23085. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  23086. each$1([
  23087. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  23088. ], function (propName) {
  23089. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  23090. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  23091. });
  23092. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  23093. zrStyle.textBaseline = 'alphabetic';
  23094. }
  23095. if (zrStyle.textBaseline === 'alphabetic') {
  23096. zrStyle.textBaseline = 'bottom';
  23097. }
  23098. if (zrStyle.textAlign === 'start') {
  23099. zrStyle.textAlign = 'left';
  23100. }
  23101. if (zrStyle.textAlign === 'end') {
  23102. zrStyle.textAlign = 'right';
  23103. }
  23104. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  23105. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  23106. ], function (propName) {
  23107. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  23108. });
  23109. if (zrStyle.lineDash) {
  23110. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  23111. }
  23112. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  23113. // enable stroke
  23114. el[elStrokeProp] = true;
  23115. }
  23116. el.__inheritedStyle = zrStyle;
  23117. }
  23118. var urlRegex = /url\(\s*#(.*?)\)/;
  23119. function getPaint(str, defs) {
  23120. // if (str === 'none') {
  23121. // return;
  23122. // }
  23123. var urlMatch = defs && str && str.match(urlRegex);
  23124. if (urlMatch) {
  23125. var url = trim(urlMatch[1]);
  23126. var def = defs[url];
  23127. return def;
  23128. }
  23129. return str;
  23130. }
  23131. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  23132. function parseTransformAttribute(xmlNode, node) {
  23133. var transform = xmlNode.getAttribute('transform');
  23134. if (transform) {
  23135. transform = transform.replace(/,/g, ' ');
  23136. var m = null;
  23137. var transformOps = [];
  23138. transform.replace(transformRegex, function (str, type, value) {
  23139. transformOps.push(type, value);
  23140. });
  23141. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  23142. var value = transformOps[i];
  23143. var type = transformOps[i - 1];
  23144. m = m || create$1();
  23145. switch (type) {
  23146. case 'translate':
  23147. value = trim(value).split(DILIMITER_REG);
  23148. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  23149. break;
  23150. case 'scale':
  23151. value = trim(value).split(DILIMITER_REG);
  23152. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  23153. break;
  23154. case 'rotate':
  23155. value = trim(value).split(DILIMITER_REG);
  23156. rotate(m, m, parseFloat(value[0]));
  23157. break;
  23158. case 'skew':
  23159. value = trim(value).split(DILIMITER_REG);
  23160. console.warn('Skew transform is not supported yet');
  23161. break;
  23162. case 'matrix':
  23163. var value = trim(value).split(DILIMITER_REG);
  23164. m[0] = parseFloat(value[0]);
  23165. m[1] = parseFloat(value[1]);
  23166. m[2] = parseFloat(value[2]);
  23167. m[3] = parseFloat(value[3]);
  23168. m[4] = parseFloat(value[4]);
  23169. m[5] = parseFloat(value[5]);
  23170. break;
  23171. }
  23172. }
  23173. node.setLocalTransform(m);
  23174. }
  23175. }
  23176. // Value may contain space.
  23177. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  23178. function parseStyleAttribute(xmlNode) {
  23179. var style = xmlNode.getAttribute('style');
  23180. var result = {};
  23181. if (!style) {
  23182. return result;
  23183. }
  23184. var styleList = {};
  23185. styleRegex.lastIndex = 0;
  23186. var styleRegResult;
  23187. while ((styleRegResult = styleRegex.exec(style)) != null) {
  23188. styleList[styleRegResult[1]] = styleRegResult[2];
  23189. }
  23190. for (var svgAttrName in attributesMap) {
  23191. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  23192. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  23193. }
  23194. }
  23195. return result;
  23196. }
  23197. /**
  23198. * @param {Array.<number>} viewBoxRect
  23199. * @param {number} width
  23200. * @param {number} height
  23201. * @return {Object} {scale, position}
  23202. */
  23203. function makeViewBoxTransform(viewBoxRect, width, height) {
  23204. var scaleX = width / viewBoxRect.width;
  23205. var scaleY = height / viewBoxRect.height;
  23206. var scale = Math.min(scaleX, scaleY);
  23207. // preserveAspectRatio 'xMidYMid'
  23208. var viewBoxScale = [scale, scale];
  23209. var viewBoxPosition = [
  23210. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  23211. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  23212. ];
  23213. return {
  23214. scale: viewBoxScale,
  23215. position: viewBoxPosition
  23216. };
  23217. }
  23218. /**
  23219. * @param {string|XMLElement} xml
  23220. * @param {Object} [opt]
  23221. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  23222. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  23223. * @param {boolean} [opt.ignoreViewBox]
  23224. * @param {boolean} [opt.ignoreRootClip]
  23225. * @return {Object} result:
  23226. * {
  23227. * root: Group, The root of the the result tree of zrender shapes,
  23228. * width: number, the viewport width of the SVG,
  23229. * height: number, the viewport height of the SVG,
  23230. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  23231. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  23232. * }
  23233. */
  23234. function parseSVG(xml, opt) {
  23235. var parser = new SVGParser();
  23236. return parser.parse(xml, opt);
  23237. }
  23238. /*
  23239. * Licensed to the Apache Software Foundation (ASF) under one
  23240. * or more contributor license agreements. See the NOTICE file
  23241. * distributed with this work for additional information
  23242. * regarding copyright ownership. The ASF licenses this file
  23243. * to you under the Apache License, Version 2.0 (the
  23244. * "License"); you may not use this file except in compliance
  23245. * with the License. You may obtain a copy of the License at
  23246. *
  23247. * http://www.apache.org/licenses/LICENSE-2.0
  23248. *
  23249. * Unless required by applicable law or agreed to in writing,
  23250. * software distributed under the License is distributed on an
  23251. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23252. * KIND, either express or implied. See the License for the
  23253. * specific language governing permissions and limitations
  23254. * under the License.
  23255. */
  23256. var storage = createHashMap();
  23257. // For minimize the code size of common echarts package,
  23258. // do not put too much logic in this module.
  23259. var mapDataStorage = {
  23260. // The format of record: see `echarts.registerMap`.
  23261. // Compatible with previous `echarts.registerMap`.
  23262. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  23263. var records;
  23264. if (isArray(rawGeoJson)) {
  23265. records = rawGeoJson;
  23266. }
  23267. else if (rawGeoJson.svg) {
  23268. records = [{
  23269. type: 'svg',
  23270. source: rawGeoJson.svg,
  23271. specialAreas: rawGeoJson.specialAreas
  23272. }];
  23273. }
  23274. else {
  23275. // Backward compatibility.
  23276. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  23277. rawSpecialAreas = rawGeoJson.specialAreas;
  23278. rawGeoJson = rawGeoJson.geoJson;
  23279. }
  23280. records = [{
  23281. type: 'geoJSON',
  23282. source: rawGeoJson,
  23283. specialAreas: rawSpecialAreas
  23284. }];
  23285. }
  23286. each$1(records, function (record) {
  23287. var type = record.type;
  23288. type === 'geoJson' && (type = record.type = 'geoJSON');
  23289. var parse = parsers[type];
  23290. if (__DEV__) {
  23291. assert$1(parse, 'Illegal map type: ' + type);
  23292. }
  23293. parse(record);
  23294. });
  23295. return storage.set(mapName, records);
  23296. },
  23297. retrieveMap: function (mapName) {
  23298. return storage.get(mapName);
  23299. }
  23300. };
  23301. var parsers = {
  23302. geoJSON: function (record) {
  23303. var source = record.source;
  23304. record.geoJSON = !isString(source)
  23305. ? source
  23306. : (typeof JSON !== 'undefined' && JSON.parse)
  23307. ? JSON.parse(source)
  23308. : (new Function('return (' + source + ');'))();
  23309. },
  23310. // Only perform parse to XML object here, which might be time
  23311. // consiming for large SVG.
  23312. // Although convert XML to zrender element is also time consiming,
  23313. // if we do it here, the clone of zrender elements has to be
  23314. // required. So we do it once for each geo instance, util real
  23315. // performance issues call for optimizing it.
  23316. svg: function (record) {
  23317. record.svgXML = parseXML(record.source);
  23318. }
  23319. };
  23320. /*
  23321. * Licensed to the Apache Software Foundation (ASF) under one
  23322. * or more contributor license agreements. See the NOTICE file
  23323. * distributed with this work for additional information
  23324. * regarding copyright ownership. The ASF licenses this file
  23325. * to you under the Apache License, Version 2.0 (the
  23326. * "License"); you may not use this file except in compliance
  23327. * with the License. You may obtain a copy of the License at
  23328. *
  23329. * http://www.apache.org/licenses/LICENSE-2.0
  23330. *
  23331. * Unless required by applicable law or agreed to in writing,
  23332. * software distributed under the License is distributed on an
  23333. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23334. * KIND, either express or implied. See the License for the
  23335. * specific language governing permissions and limitations
  23336. * under the License.
  23337. */
  23338. var assert = assert$1;
  23339. var each = each$1;
  23340. var isFunction = isFunction$1;
  23341. var isObject = isObject$1;
  23342. var parseClassType = ComponentModel.parseClassType;
  23343. var version = '4.2.1';
  23344. var dependencies = {
  23345. zrender: '4.0.6'
  23346. };
  23347. var TEST_FRAME_REMAIN_TIME = 1;
  23348. var PRIORITY_PROCESSOR_FILTER = 1000;
  23349. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  23350. var PRIORITY_VISUAL_LAYOUT = 1000;
  23351. var PRIORITY_VISUAL_GLOBAL = 2000;
  23352. var PRIORITY_VISUAL_CHART = 3000;
  23353. var PRIORITY_VISUAL_COMPONENT = 4000;
  23354. // FIXME
  23355. // necessary?
  23356. var PRIORITY_VISUAL_BRUSH = 5000;
  23357. var PRIORITY = {
  23358. PROCESSOR: {
  23359. FILTER: PRIORITY_PROCESSOR_FILTER,
  23360. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  23361. },
  23362. VISUAL: {
  23363. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  23364. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  23365. CHART: PRIORITY_VISUAL_CHART,
  23366. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  23367. BRUSH: PRIORITY_VISUAL_BRUSH
  23368. }
  23369. };
  23370. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  23371. // where they must not be invoked nestedly, except the only case: invoke
  23372. // dispatchAction with updateMethod "none" in main process.
  23373. // This flag is used to carry out this rule.
  23374. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  23375. var IN_MAIN_PROCESS = '__flagInMainProcess';
  23376. var OPTION_UPDATED = '__optionUpdated';
  23377. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  23378. function createRegisterEventWithLowercaseName(method) {
  23379. return function (eventName, handler, context) {
  23380. // Event name is all lowercase
  23381. eventName = eventName && eventName.toLowerCase();
  23382. Eventful.prototype[method].call(this, eventName, handler, context);
  23383. };
  23384. }
  23385. /**
  23386. * @module echarts~MessageCenter
  23387. */
  23388. function MessageCenter() {
  23389. Eventful.call(this);
  23390. }
  23391. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  23392. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  23393. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  23394. mixin(MessageCenter, Eventful);
  23395. /**
  23396. * @module echarts~ECharts
  23397. */
  23398. function ECharts(dom, theme$$1, opts) {
  23399. opts = opts || {};
  23400. // Get theme by name
  23401. if (typeof theme$$1 === 'string') {
  23402. theme$$1 = themeStorage[theme$$1];
  23403. }
  23404. /**
  23405. * @type {string}
  23406. */
  23407. this.id;
  23408. /**
  23409. * Group id
  23410. * @type {string}
  23411. */
  23412. this.group;
  23413. /**
  23414. * @type {HTMLElement}
  23415. * @private
  23416. */
  23417. this._dom = dom;
  23418. var defaultRenderer = 'canvas';
  23419. if (__DEV__) {
  23420. defaultRenderer = (
  23421. typeof window === 'undefined' ? global : window
  23422. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  23423. }
  23424. /**
  23425. * @type {module:zrender/ZRender}
  23426. * @private
  23427. */
  23428. var zr = this._zr = init$1(dom, {
  23429. renderer: opts.renderer || defaultRenderer,
  23430. devicePixelRatio: opts.devicePixelRatio,
  23431. width: opts.width,
  23432. height: opts.height
  23433. });
  23434. /**
  23435. * Expect 60 pfs.
  23436. * @type {Function}
  23437. * @private
  23438. */
  23439. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  23440. var theme$$1 = clone(theme$$1);
  23441. theme$$1 && backwardCompat(theme$$1, true);
  23442. /**
  23443. * @type {Object}
  23444. * @private
  23445. */
  23446. this._theme = theme$$1;
  23447. /**
  23448. * @type {Array.<module:echarts/view/Chart>}
  23449. * @private
  23450. */
  23451. this._chartsViews = [];
  23452. /**
  23453. * @type {Object.<string, module:echarts/view/Chart>}
  23454. * @private
  23455. */
  23456. this._chartsMap = {};
  23457. /**
  23458. * @type {Array.<module:echarts/view/Component>}
  23459. * @private
  23460. */
  23461. this._componentsViews = [];
  23462. /**
  23463. * @type {Object.<string, module:echarts/view/Component>}
  23464. * @private
  23465. */
  23466. this._componentsMap = {};
  23467. /**
  23468. * @type {module:echarts/CoordinateSystem}
  23469. * @private
  23470. */
  23471. this._coordSysMgr = new CoordinateSystemManager();
  23472. /**
  23473. * @type {module:echarts/ExtensionAPI}
  23474. * @private
  23475. */
  23476. var api = this._api = createExtensionAPI(this);
  23477. // Sort on demand
  23478. function prioritySortFunc(a, b) {
  23479. return a.__prio - b.__prio;
  23480. }
  23481. sort(visualFuncs, prioritySortFunc);
  23482. sort(dataProcessorFuncs, prioritySortFunc);
  23483. /**
  23484. * @type {module:echarts/stream/Scheduler}
  23485. */
  23486. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  23487. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  23488. /**
  23489. * @type {module:echarts~MessageCenter}
  23490. * @private
  23491. */
  23492. this._messageCenter = new MessageCenter();
  23493. // Init mouse events
  23494. this._initEvents();
  23495. // In case some people write `window.onresize = chart.resize`
  23496. this.resize = bind(this.resize, this);
  23497. // Can't dispatch action during rendering procedure
  23498. this._pendingActions = [];
  23499. zr.animation.on('frame', this._onframe, this);
  23500. bindRenderedEvent(zr, this);
  23501. // ECharts instance can be used as value.
  23502. setAsPrimitive(this);
  23503. }
  23504. var echartsProto = ECharts.prototype;
  23505. echartsProto._onframe = function () {
  23506. if (this._disposed) {
  23507. return;
  23508. }
  23509. var scheduler = this._scheduler;
  23510. // Lazy update
  23511. if (this[OPTION_UPDATED]) {
  23512. var silent = this[OPTION_UPDATED].silent;
  23513. this[IN_MAIN_PROCESS] = true;
  23514. prepare(this);
  23515. updateMethods.update.call(this);
  23516. this[IN_MAIN_PROCESS] = false;
  23517. this[OPTION_UPDATED] = false;
  23518. flushPendingActions.call(this, silent);
  23519. triggerUpdatedEvent.call(this, silent);
  23520. }
  23521. // Avoid do both lazy update and progress in one frame.
  23522. else if (scheduler.unfinished) {
  23523. // Stream progress.
  23524. var remainTime = TEST_FRAME_REMAIN_TIME;
  23525. var ecModel = this._model;
  23526. var api = this._api;
  23527. scheduler.unfinished = false;
  23528. do {
  23529. var startTime = +new Date();
  23530. scheduler.performSeriesTasks(ecModel);
  23531. // Currently dataProcessorFuncs do not check threshold.
  23532. scheduler.performDataProcessorTasks(ecModel);
  23533. updateStreamModes(this, ecModel);
  23534. // Do not update coordinate system here. Because that coord system update in
  23535. // each frame is not a good user experience. So we follow the rule that
  23536. // the extent of the coordinate system is determin in the first frame (the
  23537. // frame is executed immedietely after task reset.
  23538. // this._coordSysMgr.update(ecModel, api);
  23539. // console.log('--- ec frame visual ---', remainTime);
  23540. scheduler.performVisualTasks(ecModel);
  23541. renderSeries(this, this._model, api, 'remain');
  23542. remainTime -= (+new Date() - startTime);
  23543. }
  23544. while (remainTime > 0 && scheduler.unfinished);
  23545. // Call flush explicitly for trigger finished event.
  23546. if (!scheduler.unfinished) {
  23547. this._zr.flush();
  23548. }
  23549. // Else, zr flushing be ensue within the same frame,
  23550. // because zr flushing is after onframe event.
  23551. }
  23552. };
  23553. /**
  23554. * @return {HTMLElement}
  23555. */
  23556. echartsProto.getDom = function () {
  23557. return this._dom;
  23558. };
  23559. /**
  23560. * @return {module:zrender~ZRender}
  23561. */
  23562. echartsProto.getZr = function () {
  23563. return this._zr;
  23564. };
  23565. /**
  23566. * Usage:
  23567. * chart.setOption(option, notMerge, lazyUpdate);
  23568. * chart.setOption(option, {
  23569. * notMerge: ...,
  23570. * lazyUpdate: ...,
  23571. * silent: ...
  23572. * });
  23573. *
  23574. * @param {Object} option
  23575. * @param {Object|boolean} [opts] opts or notMerge.
  23576. * @param {boolean} [opts.notMerge=false]
  23577. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  23578. */
  23579. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  23580. if (__DEV__) {
  23581. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  23582. }
  23583. var silent;
  23584. if (isObject(notMerge)) {
  23585. lazyUpdate = notMerge.lazyUpdate;
  23586. silent = notMerge.silent;
  23587. notMerge = notMerge.notMerge;
  23588. }
  23589. this[IN_MAIN_PROCESS] = true;
  23590. if (!this._model || notMerge) {
  23591. var optionManager = new OptionManager(this._api);
  23592. var theme$$1 = this._theme;
  23593. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  23594. ecModel.scheduler = this._scheduler;
  23595. ecModel.init(null, null, theme$$1, optionManager);
  23596. }
  23597. this._model.setOption(option, optionPreprocessorFuncs);
  23598. if (lazyUpdate) {
  23599. this[OPTION_UPDATED] = {silent: silent};
  23600. this[IN_MAIN_PROCESS] = false;
  23601. }
  23602. else {
  23603. prepare(this);
  23604. updateMethods.update.call(this);
  23605. // Ensure zr refresh sychronously, and then pixel in canvas can be
  23606. // fetched after `setOption`.
  23607. this._zr.flush();
  23608. this[OPTION_UPDATED] = false;
  23609. this[IN_MAIN_PROCESS] = false;
  23610. flushPendingActions.call(this, silent);
  23611. triggerUpdatedEvent.call(this, silent);
  23612. }
  23613. };
  23614. /**
  23615. * @DEPRECATED
  23616. */
  23617. echartsProto.setTheme = function () {
  23618. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  23619. };
  23620. /**
  23621. * @return {module:echarts/model/Global}
  23622. */
  23623. echartsProto.getModel = function () {
  23624. return this._model;
  23625. };
  23626. /**
  23627. * @return {Object}
  23628. */
  23629. echartsProto.getOption = function () {
  23630. return this._model && this._model.getOption();
  23631. };
  23632. /**
  23633. * @return {number}
  23634. */
  23635. echartsProto.getWidth = function () {
  23636. return this._zr.getWidth();
  23637. };
  23638. /**
  23639. * @return {number}
  23640. */
  23641. echartsProto.getHeight = function () {
  23642. return this._zr.getHeight();
  23643. };
  23644. /**
  23645. * @return {number}
  23646. */
  23647. echartsProto.getDevicePixelRatio = function () {
  23648. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  23649. };
  23650. /**
  23651. * Get canvas which has all thing rendered
  23652. * @param {Object} opts
  23653. * @param {string} [opts.backgroundColor]
  23654. * @return {string}
  23655. */
  23656. echartsProto.getRenderedCanvas = function (opts) {
  23657. if (!env$1.canvasSupported) {
  23658. return;
  23659. }
  23660. opts = opts || {};
  23661. opts.pixelRatio = opts.pixelRatio || 1;
  23662. opts.backgroundColor = opts.backgroundColor
  23663. || this._model.get('backgroundColor');
  23664. var zr = this._zr;
  23665. // var list = zr.storage.getDisplayList();
  23666. // Stop animations
  23667. // Never works before in init animation, so remove it.
  23668. // zrUtil.each(list, function (el) {
  23669. // el.stopAnimation(true);
  23670. // });
  23671. return zr.painter.getRenderedCanvas(opts);
  23672. };
  23673. /**
  23674. * Get svg data url
  23675. * @return {string}
  23676. */
  23677. echartsProto.getSvgDataUrl = function () {
  23678. if (!env$1.svgSupported) {
  23679. return;
  23680. }
  23681. var zr = this._zr;
  23682. var list = zr.storage.getDisplayList();
  23683. // Stop animations
  23684. each$1(list, function (el) {
  23685. el.stopAnimation(true);
  23686. });
  23687. return zr.painter.pathToDataUrl();
  23688. };
  23689. /**
  23690. * @return {string}
  23691. * @param {Object} opts
  23692. * @param {string} [opts.type='png']
  23693. * @param {string} [opts.pixelRatio=1]
  23694. * @param {string} [opts.backgroundColor]
  23695. * @param {string} [opts.excludeComponents]
  23696. */
  23697. echartsProto.getDataURL = function (opts) {
  23698. opts = opts || {};
  23699. var excludeComponents = opts.excludeComponents;
  23700. var ecModel = this._model;
  23701. var excludesComponentViews = [];
  23702. var self = this;
  23703. each(excludeComponents, function (componentType) {
  23704. ecModel.eachComponent({
  23705. mainType: componentType
  23706. }, function (component) {
  23707. var view = self._componentsMap[component.__viewId];
  23708. if (!view.group.ignore) {
  23709. excludesComponentViews.push(view);
  23710. view.group.ignore = true;
  23711. }
  23712. });
  23713. });
  23714. var url = this._zr.painter.getType() === 'svg'
  23715. ? this.getSvgDataUrl()
  23716. : this.getRenderedCanvas(opts).toDataURL(
  23717. 'image/' + (opts && opts.type || 'png')
  23718. );
  23719. each(excludesComponentViews, function (view) {
  23720. view.group.ignore = false;
  23721. });
  23722. return url;
  23723. };
  23724. /**
  23725. * @return {string}
  23726. * @param {Object} opts
  23727. * @param {string} [opts.type='png']
  23728. * @param {string} [opts.pixelRatio=1]
  23729. * @param {string} [opts.backgroundColor]
  23730. */
  23731. echartsProto.getConnectedDataURL = function (opts) {
  23732. if (!env$1.canvasSupported) {
  23733. return;
  23734. }
  23735. var groupId = this.group;
  23736. var mathMin = Math.min;
  23737. var mathMax = Math.max;
  23738. var MAX_NUMBER = Infinity;
  23739. if (connectedGroups[groupId]) {
  23740. var left = MAX_NUMBER;
  23741. var top = MAX_NUMBER;
  23742. var right = -MAX_NUMBER;
  23743. var bottom = -MAX_NUMBER;
  23744. var canvasList = [];
  23745. var dpr = (opts && opts.pixelRatio) || 1;
  23746. each$1(instances, function (chart, id) {
  23747. if (chart.group === groupId) {
  23748. var canvas = chart.getRenderedCanvas(
  23749. clone(opts)
  23750. );
  23751. var boundingRect = chart.getDom().getBoundingClientRect();
  23752. left = mathMin(boundingRect.left, left);
  23753. top = mathMin(boundingRect.top, top);
  23754. right = mathMax(boundingRect.right, right);
  23755. bottom = mathMax(boundingRect.bottom, bottom);
  23756. canvasList.push({
  23757. dom: canvas,
  23758. left: boundingRect.left,
  23759. top: boundingRect.top
  23760. });
  23761. }
  23762. });
  23763. left *= dpr;
  23764. top *= dpr;
  23765. right *= dpr;
  23766. bottom *= dpr;
  23767. var width = right - left;
  23768. var height = bottom - top;
  23769. var targetCanvas = createCanvas();
  23770. targetCanvas.width = width;
  23771. targetCanvas.height = height;
  23772. var zr = init$1(targetCanvas);
  23773. each(canvasList, function (item) {
  23774. var img = new ZImage({
  23775. style: {
  23776. x: item.left * dpr - left,
  23777. y: item.top * dpr - top,
  23778. image: item.dom
  23779. }
  23780. });
  23781. zr.add(img);
  23782. });
  23783. zr.refreshImmediately();
  23784. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  23785. }
  23786. else {
  23787. return this.getDataURL(opts);
  23788. }
  23789. };
  23790. /**
  23791. * Convert from logical coordinate system to pixel coordinate system.
  23792. * See CoordinateSystem#convertToPixel.
  23793. * @param {string|Object} finder
  23794. * If string, e.g., 'geo', means {geoIndex: 0}.
  23795. * If Object, could contain some of these properties below:
  23796. * {
  23797. * seriesIndex / seriesId / seriesName,
  23798. * geoIndex / geoId, geoName,
  23799. * bmapIndex / bmapId / bmapName,
  23800. * xAxisIndex / xAxisId / xAxisName,
  23801. * yAxisIndex / yAxisId / yAxisName,
  23802. * gridIndex / gridId / gridName,
  23803. * ... (can be extended)
  23804. * }
  23805. * @param {Array|number} value
  23806. * @return {Array|number} result
  23807. */
  23808. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  23809. /**
  23810. * Convert from pixel coordinate system to logical coordinate system.
  23811. * See CoordinateSystem#convertFromPixel.
  23812. * @param {string|Object} finder
  23813. * If string, e.g., 'geo', means {geoIndex: 0}.
  23814. * If Object, could contain some of these properties below:
  23815. * {
  23816. * seriesIndex / seriesId / seriesName,
  23817. * geoIndex / geoId / geoName,
  23818. * bmapIndex / bmapId / bmapName,
  23819. * xAxisIndex / xAxisId / xAxisName,
  23820. * yAxisIndex / yAxisId / yAxisName
  23821. * gridIndex / gridId / gridName,
  23822. * ... (can be extended)
  23823. * }
  23824. * @param {Array|number} value
  23825. * @return {Array|number} result
  23826. */
  23827. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  23828. function doConvertPixel(methodName, finder, value) {
  23829. var ecModel = this._model;
  23830. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  23831. var result;
  23832. finder = parseFinder(ecModel, finder);
  23833. for (var i = 0; i < coordSysList.length; i++) {
  23834. var coordSys = coordSysList[i];
  23835. if (coordSys[methodName]
  23836. && (result = coordSys[methodName](ecModel, finder, value)) != null
  23837. ) {
  23838. return result;
  23839. }
  23840. }
  23841. if (__DEV__) {
  23842. console.warn(
  23843. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  23844. );
  23845. }
  23846. }
  23847. /**
  23848. * Is the specified coordinate systems or components contain the given pixel point.
  23849. * @param {string|Object} finder
  23850. * If string, e.g., 'geo', means {geoIndex: 0}.
  23851. * If Object, could contain some of these properties below:
  23852. * {
  23853. * seriesIndex / seriesId / seriesName,
  23854. * geoIndex / geoId / geoName,
  23855. * bmapIndex / bmapId / bmapName,
  23856. * xAxisIndex / xAxisId / xAxisName,
  23857. * yAxisIndex / yAxisId / yAxisName,
  23858. * gridIndex / gridId / gridName,
  23859. * ... (can be extended)
  23860. * }
  23861. * @param {Array|number} value
  23862. * @return {boolean} result
  23863. */
  23864. echartsProto.containPixel = function (finder, value) {
  23865. var ecModel = this._model;
  23866. var result;
  23867. finder = parseFinder(ecModel, finder);
  23868. each$1(finder, function (models, key) {
  23869. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  23870. var coordSys = model.coordinateSystem;
  23871. if (coordSys && coordSys.containPoint) {
  23872. result |= !!coordSys.containPoint(value);
  23873. }
  23874. else if (key === 'seriesModels') {
  23875. var view = this._chartsMap[model.__viewId];
  23876. if (view && view.containPoint) {
  23877. result |= view.containPoint(value, model);
  23878. }
  23879. else {
  23880. if (__DEV__) {
  23881. console.warn(key + ': ' + (view
  23882. ? 'The found component do not support containPoint.'
  23883. : 'No view mapping to the found component.'
  23884. ));
  23885. }
  23886. }
  23887. }
  23888. else {
  23889. if (__DEV__) {
  23890. console.warn(key + ': containPoint is not supported');
  23891. }
  23892. }
  23893. }, this);
  23894. }, this);
  23895. return !!result;
  23896. };
  23897. /**
  23898. * Get visual from series or data.
  23899. * @param {string|Object} finder
  23900. * If string, e.g., 'series', means {seriesIndex: 0}.
  23901. * If Object, could contain some of these properties below:
  23902. * {
  23903. * seriesIndex / seriesId / seriesName,
  23904. * dataIndex / dataIndexInside
  23905. * }
  23906. * If dataIndex is not specified, series visual will be fetched,
  23907. * but not data item visual.
  23908. * If all of seriesIndex, seriesId, seriesName are not specified,
  23909. * visual will be fetched from first series.
  23910. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  23911. */
  23912. echartsProto.getVisual = function (finder, visualType) {
  23913. var ecModel = this._model;
  23914. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  23915. var seriesModel = finder.seriesModel;
  23916. if (__DEV__) {
  23917. if (!seriesModel) {
  23918. console.warn('There is no specified seires model');
  23919. }
  23920. }
  23921. var data = seriesModel.getData();
  23922. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  23923. ? finder.dataIndexInside
  23924. : finder.hasOwnProperty('dataIndex')
  23925. ? data.indexOfRawIndex(finder.dataIndex)
  23926. : null;
  23927. return dataIndexInside != null
  23928. ? data.getItemVisual(dataIndexInside, visualType)
  23929. : data.getVisual(visualType);
  23930. };
  23931. /**
  23932. * Get view of corresponding component model
  23933. * @param {module:echarts/model/Component} componentModel
  23934. * @return {module:echarts/view/Component}
  23935. */
  23936. echartsProto.getViewOfComponentModel = function (componentModel) {
  23937. return this._componentsMap[componentModel.__viewId];
  23938. };
  23939. /**
  23940. * Get view of corresponding series model
  23941. * @param {module:echarts/model/Series} seriesModel
  23942. * @return {module:echarts/view/Chart}
  23943. */
  23944. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  23945. return this._chartsMap[seriesModel.__viewId];
  23946. };
  23947. var updateMethods = {
  23948. prepareAndUpdate: function (payload) {
  23949. prepare(this);
  23950. updateMethods.update.call(this, payload);
  23951. },
  23952. /**
  23953. * @param {Object} payload
  23954. * @private
  23955. */
  23956. update: function (payload) {
  23957. // console.profile && console.profile('update');
  23958. var ecModel = this._model;
  23959. var api = this._api;
  23960. var zr = this._zr;
  23961. var coordSysMgr = this._coordSysMgr;
  23962. var scheduler = this._scheduler;
  23963. // update before setOption
  23964. if (!ecModel) {
  23965. return;
  23966. }
  23967. scheduler.restoreData(ecModel, payload);
  23968. scheduler.performSeriesTasks(ecModel);
  23969. // TODO
  23970. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  23971. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  23972. // Create new coordinate system each update
  23973. // In LineView may save the old coordinate system and use it to get the orignal point
  23974. coordSysMgr.create(ecModel, api);
  23975. scheduler.performDataProcessorTasks(ecModel, payload);
  23976. // Current stream render is not supported in data process. So we can update
  23977. // stream modes after data processing, where the filtered data is used to
  23978. // deteming whether use progressive rendering.
  23979. updateStreamModes(this, ecModel);
  23980. // We update stream modes before coordinate system updated, then the modes info
  23981. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  23982. // the drawback is the full coord info can not be fetched. Fortunately this full
  23983. // coord is not requied in stream mode updater currently.
  23984. coordSysMgr.update(ecModel, api);
  23985. clearColorPalette(ecModel);
  23986. scheduler.performVisualTasks(ecModel, payload);
  23987. render(this, ecModel, api, payload);
  23988. // Set background
  23989. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  23990. // In IE8
  23991. if (!env$1.canvasSupported) {
  23992. var colorArr = parse(backgroundColor);
  23993. backgroundColor = stringify(colorArr, 'rgb');
  23994. if (colorArr[3] === 0) {
  23995. backgroundColor = 'transparent';
  23996. }
  23997. }
  23998. else {
  23999. zr.setBackgroundColor(backgroundColor);
  24000. }
  24001. performPostUpdateFuncs(ecModel, api);
  24002. // console.profile && console.profileEnd('update');
  24003. },
  24004. /**
  24005. * @param {Object} payload
  24006. * @private
  24007. */
  24008. updateTransform: function (payload) {
  24009. var ecModel = this._model;
  24010. var ecIns = this;
  24011. var api = this._api;
  24012. // update before setOption
  24013. if (!ecModel) {
  24014. return;
  24015. }
  24016. // ChartView.markUpdateMethod(payload, 'updateTransform');
  24017. var componentDirtyList = [];
  24018. ecModel.eachComponent(function (componentType, componentModel) {
  24019. var componentView = ecIns.getViewOfComponentModel(componentModel);
  24020. if (componentView && componentView.__alive) {
  24021. if (componentView.updateTransform) {
  24022. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24023. result && result.update && componentDirtyList.push(componentView);
  24024. }
  24025. else {
  24026. componentDirtyList.push(componentView);
  24027. }
  24028. }
  24029. });
  24030. var seriesDirtyMap = createHashMap();
  24031. ecModel.eachSeries(function (seriesModel) {
  24032. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24033. if (chartView.updateTransform) {
  24034. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24035. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24036. }
  24037. else {
  24038. seriesDirtyMap.set(seriesModel.uid, 1);
  24039. }
  24040. });
  24041. clearColorPalette(ecModel);
  24042. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24043. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24044. this._scheduler.performVisualTasks(
  24045. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  24046. );
  24047. // Currently, not call render of components. Geo render cost a lot.
  24048. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  24049. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  24050. performPostUpdateFuncs(ecModel, this._api);
  24051. },
  24052. /**
  24053. * @param {Object} payload
  24054. * @private
  24055. */
  24056. updateView: function (payload) {
  24057. var ecModel = this._model;
  24058. // update before setOption
  24059. if (!ecModel) {
  24060. return;
  24061. }
  24062. Chart.markUpdateMethod(payload, 'updateView');
  24063. clearColorPalette(ecModel);
  24064. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24065. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24066. render(this, this._model, this._api, payload);
  24067. performPostUpdateFuncs(ecModel, this._api);
  24068. },
  24069. /**
  24070. * @param {Object} payload
  24071. * @private
  24072. */
  24073. updateVisual: function (payload) {
  24074. updateMethods.update.call(this, payload);
  24075. // var ecModel = this._model;
  24076. // // update before setOption
  24077. // if (!ecModel) {
  24078. // return;
  24079. // }
  24080. // ChartView.markUpdateMethod(payload, 'updateVisual');
  24081. // clearColorPalette(ecModel);
  24082. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24083. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  24084. // render(this, this._model, this._api, payload);
  24085. // performPostUpdateFuncs(ecModel, this._api);
  24086. },
  24087. /**
  24088. * @param {Object} payload
  24089. * @private
  24090. */
  24091. updateLayout: function (payload) {
  24092. updateMethods.update.call(this, payload);
  24093. // var ecModel = this._model;
  24094. // // update before setOption
  24095. // if (!ecModel) {
  24096. // return;
  24097. // }
  24098. // ChartView.markUpdateMethod(payload, 'updateLayout');
  24099. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24100. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24101. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24102. // render(this, this._model, this._api, payload);
  24103. // performPostUpdateFuncs(ecModel, this._api);
  24104. }
  24105. };
  24106. function prepare(ecIns) {
  24107. var ecModel = ecIns._model;
  24108. var scheduler = ecIns._scheduler;
  24109. scheduler.restorePipelines(ecModel);
  24110. scheduler.prepareStageTasks();
  24111. prepareView(ecIns, 'component', ecModel, scheduler);
  24112. prepareView(ecIns, 'chart', ecModel, scheduler);
  24113. scheduler.plan();
  24114. }
  24115. /**
  24116. * @private
  24117. */
  24118. function updateDirectly(ecIns, method, payload, mainType, subType) {
  24119. var ecModel = ecIns._model;
  24120. // broadcast
  24121. if (!mainType) {
  24122. // FIXME
  24123. // Chart will not be update directly here, except set dirty.
  24124. // But there is no such scenario now.
  24125. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  24126. return;
  24127. }
  24128. var query = {};
  24129. query[mainType + 'Id'] = payload[mainType + 'Id'];
  24130. query[mainType + 'Index'] = payload[mainType + 'Index'];
  24131. query[mainType + 'Name'] = payload[mainType + 'Name'];
  24132. var condition = {mainType: mainType, query: query};
  24133. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  24134. var excludeSeriesId = payload.excludeSeriesId;
  24135. if (excludeSeriesId != null) {
  24136. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  24137. }
  24138. // If dispatchAction before setOption, do nothing.
  24139. ecModel && ecModel.eachComponent(condition, function (model) {
  24140. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  24141. callView(ecIns[
  24142. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24143. ][model.__viewId]);
  24144. }
  24145. }, ecIns);
  24146. function callView(view) {
  24147. view && view.__alive && view[method] && view[method](
  24148. view.__model, ecModel, ecIns._api, payload
  24149. );
  24150. }
  24151. }
  24152. /**
  24153. * Resize the chart
  24154. * @param {Object} opts
  24155. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  24156. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  24157. * @param {boolean} [opts.silent=false]
  24158. */
  24159. echartsProto.resize = function (opts) {
  24160. if (__DEV__) {
  24161. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  24162. }
  24163. this._zr.resize(opts);
  24164. var ecModel = this._model;
  24165. // Resize loading effect
  24166. this._loadingFX && this._loadingFX.resize();
  24167. if (!ecModel) {
  24168. return;
  24169. }
  24170. var optionChanged = ecModel.resetOption('media');
  24171. var silent = opts && opts.silent;
  24172. this[IN_MAIN_PROCESS] = true;
  24173. optionChanged && prepare(this);
  24174. updateMethods.update.call(this);
  24175. this[IN_MAIN_PROCESS] = false;
  24176. flushPendingActions.call(this, silent);
  24177. triggerUpdatedEvent.call(this, silent);
  24178. };
  24179. function updateStreamModes(ecIns, ecModel) {
  24180. var chartsMap = ecIns._chartsMap;
  24181. var scheduler = ecIns._scheduler;
  24182. ecModel.eachSeries(function (seriesModel) {
  24183. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  24184. });
  24185. }
  24186. /**
  24187. * Show loading effect
  24188. * @param {string} [name='default']
  24189. * @param {Object} [cfg]
  24190. */
  24191. echartsProto.showLoading = function (name, cfg) {
  24192. if (isObject(name)) {
  24193. cfg = name;
  24194. name = '';
  24195. }
  24196. name = name || 'default';
  24197. this.hideLoading();
  24198. if (!loadingEffects[name]) {
  24199. if (__DEV__) {
  24200. console.warn('Loading effects ' + name + ' not exists.');
  24201. }
  24202. return;
  24203. }
  24204. var el = loadingEffects[name](this._api, cfg);
  24205. var zr = this._zr;
  24206. this._loadingFX = el;
  24207. zr.add(el);
  24208. };
  24209. /**
  24210. * Hide loading effect
  24211. */
  24212. echartsProto.hideLoading = function () {
  24213. this._loadingFX && this._zr.remove(this._loadingFX);
  24214. this._loadingFX = null;
  24215. };
  24216. /**
  24217. * @param {Object} eventObj
  24218. * @return {Object}
  24219. */
  24220. echartsProto.makeActionFromEvent = function (eventObj) {
  24221. var payload = extend({}, eventObj);
  24222. payload.type = eventActionMap[eventObj.type];
  24223. return payload;
  24224. };
  24225. /**
  24226. * @pubilc
  24227. * @param {Object} payload
  24228. * @param {string} [payload.type] Action type
  24229. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  24230. * @param {boolean} [opt.silent=false] Whether trigger events.
  24231. * @param {boolean} [opt.flush=undefined]
  24232. * true: Flush immediately, and then pixel in canvas can be fetched
  24233. * immediately. Caution: it might affect performance.
  24234. * false: Not not flush.
  24235. * undefined: Auto decide whether perform flush.
  24236. */
  24237. echartsProto.dispatchAction = function (payload, opt) {
  24238. if (!isObject(opt)) {
  24239. opt = {silent: !!opt};
  24240. }
  24241. if (!actions[payload.type]) {
  24242. return;
  24243. }
  24244. // Avoid dispatch action before setOption. Especially in `connect`.
  24245. if (!this._model) {
  24246. return;
  24247. }
  24248. // May dispatchAction in rendering procedure
  24249. if (this[IN_MAIN_PROCESS]) {
  24250. this._pendingActions.push(payload);
  24251. return;
  24252. }
  24253. doDispatchAction.call(this, payload, opt.silent);
  24254. if (opt.flush) {
  24255. this._zr.flush(true);
  24256. }
  24257. else if (opt.flush !== false && env$1.browser.weChat) {
  24258. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  24259. // hang when sliding page (on touch event), which cause that zr does not
  24260. // refresh util user interaction finished, which is not expected.
  24261. // But `dispatchAction` may be called too frequently when pan on touch
  24262. // screen, which impacts performance if do not throttle them.
  24263. this._throttledZrFlush();
  24264. }
  24265. flushPendingActions.call(this, opt.silent);
  24266. triggerUpdatedEvent.call(this, opt.silent);
  24267. };
  24268. function doDispatchAction(payload, silent) {
  24269. var payloadType = payload.type;
  24270. var escapeConnect = payload.escapeConnect;
  24271. var actionWrap = actions[payloadType];
  24272. var actionInfo = actionWrap.actionInfo;
  24273. var cptType = (actionInfo.update || 'update').split(':');
  24274. var updateMethod = cptType.pop();
  24275. cptType = cptType[0] != null && parseClassType(cptType[0]);
  24276. this[IN_MAIN_PROCESS] = true;
  24277. var payloads = [payload];
  24278. var batched = false;
  24279. // Batch action
  24280. if (payload.batch) {
  24281. batched = true;
  24282. payloads = map(payload.batch, function (item) {
  24283. item = defaults(extend({}, item), payload);
  24284. item.batch = null;
  24285. return item;
  24286. });
  24287. }
  24288. var eventObjBatch = [];
  24289. var eventObj;
  24290. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  24291. each(payloads, function (batchItem) {
  24292. // Action can specify the event by return it.
  24293. eventObj = actionWrap.action(batchItem, this._model, this._api);
  24294. // Emit event outside
  24295. eventObj = eventObj || extend({}, batchItem);
  24296. // Convert type to eventType
  24297. eventObj.type = actionInfo.event || eventObj.type;
  24298. eventObjBatch.push(eventObj);
  24299. // light update does not perform data process, layout and visual.
  24300. if (isHighDown) {
  24301. // method, payload, mainType, subType
  24302. updateDirectly(this, updateMethod, batchItem, 'series');
  24303. }
  24304. else if (cptType) {
  24305. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  24306. }
  24307. }, this);
  24308. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  24309. // Still dirty
  24310. if (this[OPTION_UPDATED]) {
  24311. // FIXME Pass payload ?
  24312. prepare(this);
  24313. updateMethods.update.call(this, payload);
  24314. this[OPTION_UPDATED] = false;
  24315. }
  24316. else {
  24317. updateMethods[updateMethod].call(this, payload);
  24318. }
  24319. }
  24320. // Follow the rule of action batch
  24321. if (batched) {
  24322. eventObj = {
  24323. type: actionInfo.event || payloadType,
  24324. escapeConnect: escapeConnect,
  24325. batch: eventObjBatch
  24326. };
  24327. }
  24328. else {
  24329. eventObj = eventObjBatch[0];
  24330. }
  24331. this[IN_MAIN_PROCESS] = false;
  24332. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  24333. }
  24334. function flushPendingActions(silent) {
  24335. var pendingActions = this._pendingActions;
  24336. while (pendingActions.length) {
  24337. var payload = pendingActions.shift();
  24338. doDispatchAction.call(this, payload, silent);
  24339. }
  24340. }
  24341. function triggerUpdatedEvent(silent) {
  24342. !silent && this.trigger('updated');
  24343. }
  24344. /**
  24345. * Event `rendered` is triggered when zr
  24346. * rendered. It is useful for realtime
  24347. * snapshot (reflect animation).
  24348. *
  24349. * Event `finished` is triggered when:
  24350. * (1) zrender rendering finished.
  24351. * (2) initial animation finished.
  24352. * (3) progressive rendering finished.
  24353. * (4) no pending action.
  24354. * (5) no delayed setOption needs to be processed.
  24355. */
  24356. function bindRenderedEvent(zr, ecIns) {
  24357. zr.on('rendered', function () {
  24358. ecIns.trigger('rendered');
  24359. // The `finished` event should not be triggered repeatly,
  24360. // so it should only be triggered when rendering indeed happend
  24361. // in zrender. (Consider the case that dipatchAction is keep
  24362. // triggering when mouse move).
  24363. if (
  24364. // Although zr is dirty if initial animation is not finished
  24365. // and this checking is called on frame, we also check
  24366. // animation finished for robustness.
  24367. zr.animation.isFinished()
  24368. && !ecIns[OPTION_UPDATED]
  24369. && !ecIns._scheduler.unfinished
  24370. && !ecIns._pendingActions.length
  24371. ) {
  24372. ecIns.trigger('finished');
  24373. }
  24374. });
  24375. }
  24376. /**
  24377. * @param {Object} params
  24378. * @param {number} params.seriesIndex
  24379. * @param {Array|TypedArray} params.data
  24380. */
  24381. echartsProto.appendData = function (params) {
  24382. var seriesIndex = params.seriesIndex;
  24383. var ecModel = this.getModel();
  24384. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  24385. if (__DEV__) {
  24386. assert(params.data && seriesModel);
  24387. }
  24388. seriesModel.appendData(params);
  24389. // Note: `appendData` does not support that update extent of coordinate
  24390. // system, util some scenario require that. In the expected usage of
  24391. // `appendData`, the initial extent of coordinate system should better
  24392. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  24393. // the extent changed while `appendData`, the location of the painted
  24394. // graphic elements have to be changed, which make the usage of
  24395. // `appendData` meaningless.
  24396. this._scheduler.unfinished = true;
  24397. };
  24398. /**
  24399. * Register event
  24400. * @method
  24401. */
  24402. echartsProto.on = createRegisterEventWithLowercaseName('on');
  24403. echartsProto.off = createRegisterEventWithLowercaseName('off');
  24404. echartsProto.one = createRegisterEventWithLowercaseName('one');
  24405. /**
  24406. * Prepare view instances of charts and components
  24407. * @param {module:echarts/model/Global} ecModel
  24408. * @private
  24409. */
  24410. function prepareView(ecIns, type, ecModel, scheduler) {
  24411. var isComponent = type === 'component';
  24412. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  24413. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  24414. var zr = ecIns._zr;
  24415. var api = ecIns._api;
  24416. for (var i = 0; i < viewList.length; i++) {
  24417. viewList[i].__alive = false;
  24418. }
  24419. isComponent
  24420. ? ecModel.eachComponent(function (componentType, model) {
  24421. componentType !== 'series' && doPrepare(model);
  24422. })
  24423. : ecModel.eachSeries(doPrepare);
  24424. function doPrepare(model) {
  24425. // Consider: id same and type changed.
  24426. var viewId = '_ec_' + model.id + '_' + model.type;
  24427. var view = viewMap[viewId];
  24428. if (!view) {
  24429. var classType = parseClassType(model.type);
  24430. var Clazz = isComponent
  24431. ? Component.getClass(classType.main, classType.sub)
  24432. : Chart.getClass(classType.sub);
  24433. if (__DEV__) {
  24434. assert(Clazz, classType.sub + ' does not exist.');
  24435. }
  24436. view = new Clazz();
  24437. view.init(ecModel, api);
  24438. viewMap[viewId] = view;
  24439. viewList.push(view);
  24440. zr.add(view.group);
  24441. }
  24442. model.__viewId = view.__id = viewId;
  24443. view.__alive = true;
  24444. view.__model = model;
  24445. view.group.__ecComponentInfo = {
  24446. mainType: model.mainType,
  24447. index: model.componentIndex
  24448. };
  24449. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  24450. }
  24451. for (var i = 0; i < viewList.length;) {
  24452. var view = viewList[i];
  24453. if (!view.__alive) {
  24454. !isComponent && view.renderTask.dispose();
  24455. zr.remove(view.group);
  24456. view.dispose(ecModel, api);
  24457. viewList.splice(i, 1);
  24458. delete viewMap[view.__id];
  24459. view.__id = view.group.__ecComponentInfo = null;
  24460. }
  24461. else {
  24462. i++;
  24463. }
  24464. }
  24465. }
  24466. // /**
  24467. // * Encode visual infomation from data after data processing
  24468. // *
  24469. // * @param {module:echarts/model/Global} ecModel
  24470. // * @param {object} layout
  24471. // * @param {boolean} [layoutFilter] `true`: only layout,
  24472. // * `false`: only not layout,
  24473. // * `null`/`undefined`: all.
  24474. // * @param {string} taskBaseTag
  24475. // * @private
  24476. // */
  24477. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  24478. // each(visualFuncs, function (visual, index) {
  24479. // var isLayout = visual.isLayout;
  24480. // if (layoutFilter == null
  24481. // || (layoutFilter === false && !isLayout)
  24482. // || (layoutFilter === true && isLayout)
  24483. // ) {
  24484. // visual.func(ecModel, api, payload);
  24485. // }
  24486. // });
  24487. // }
  24488. function clearColorPalette(ecModel) {
  24489. ecModel.clearColorPalette();
  24490. ecModel.eachSeries(function (seriesModel) {
  24491. seriesModel.clearColorPalette();
  24492. });
  24493. }
  24494. function render(ecIns, ecModel, api, payload) {
  24495. renderComponents(ecIns, ecModel, api, payload);
  24496. each(ecIns._chartsViews, function (chart) {
  24497. chart.__alive = false;
  24498. });
  24499. renderSeries(ecIns, ecModel, api, payload);
  24500. // Remove groups of unrendered charts
  24501. each(ecIns._chartsViews, function (chart) {
  24502. if (!chart.__alive) {
  24503. chart.remove(ecModel, api);
  24504. }
  24505. });
  24506. }
  24507. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  24508. each(dirtyList || ecIns._componentsViews, function (componentView) {
  24509. var componentModel = componentView.__model;
  24510. componentView.render(componentModel, ecModel, api, payload);
  24511. updateZ(componentModel, componentView);
  24512. });
  24513. }
  24514. /**
  24515. * Render each chart and component
  24516. * @private
  24517. */
  24518. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  24519. // Render all charts
  24520. var scheduler = ecIns._scheduler;
  24521. var unfinished;
  24522. ecModel.eachSeries(function (seriesModel) {
  24523. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24524. chartView.__alive = true;
  24525. var renderTask = chartView.renderTask;
  24526. scheduler.updatePayload(renderTask, payload);
  24527. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  24528. renderTask.dirty();
  24529. }
  24530. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  24531. chartView.group.silent = !!seriesModel.get('silent');
  24532. updateZ(seriesModel, chartView);
  24533. updateBlend(seriesModel, chartView);
  24534. });
  24535. scheduler.unfinished |= unfinished;
  24536. // If use hover layer
  24537. updateHoverLayerStatus(ecIns._zr, ecModel);
  24538. // Add aria
  24539. aria(ecIns._zr.dom, ecModel);
  24540. }
  24541. function performPostUpdateFuncs(ecModel, api) {
  24542. each(postUpdateFuncs, function (func) {
  24543. func(ecModel, api);
  24544. });
  24545. }
  24546. var MOUSE_EVENT_NAMES = [
  24547. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  24548. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  24549. ];
  24550. /**
  24551. * @private
  24552. */
  24553. echartsProto._initEvents = function () {
  24554. each(MOUSE_EVENT_NAMES, function (eveName) {
  24555. var handler = function (e) {
  24556. var ecModel = this.getModel();
  24557. var el = e.target;
  24558. var params;
  24559. var isGlobalOut = eveName === 'globalout';
  24560. // no e.target when 'globalout'.
  24561. if (isGlobalOut) {
  24562. params = {};
  24563. }
  24564. else if (el && el.dataIndex != null) {
  24565. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  24566. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  24567. }
  24568. // If element has custom eventData of components
  24569. else if (el && el.eventData) {
  24570. params = extend({}, el.eventData);
  24571. }
  24572. // Contract: if params prepared in mouse event,
  24573. // these properties must be specified:
  24574. // {
  24575. // componentType: string (component main type)
  24576. // componentIndex: number
  24577. // }
  24578. // Otherwise event query can not work.
  24579. if (params) {
  24580. var componentType = params.componentType;
  24581. var componentIndex = params.componentIndex;
  24582. // Special handling for historic reason: when trigger by
  24583. // markLine/markPoint/markArea, the componentType is
  24584. // 'markLine'/'markPoint'/'markArea', but we should better
  24585. // enable them to be queried by seriesIndex, since their
  24586. // option is set in each series.
  24587. if (componentType === 'markLine'
  24588. || componentType === 'markPoint'
  24589. || componentType === 'markArea'
  24590. ) {
  24591. componentType = 'series';
  24592. componentIndex = params.seriesIndex;
  24593. }
  24594. var model = componentType && componentIndex != null
  24595. && ecModel.getComponent(componentType, componentIndex);
  24596. var view = model && this[
  24597. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24598. ][model.__viewId];
  24599. if (__DEV__) {
  24600. // `event.componentType` and `event[componentTpype + 'Index']` must not
  24601. // be missed, otherwise there is no way to distinguish source component.
  24602. // See `dataFormat.getDataParams`.
  24603. if (!isGlobalOut && !(model && view)) {
  24604. console.warn('model or view can not be found by params');
  24605. }
  24606. }
  24607. params.event = e;
  24608. params.type = eveName;
  24609. this._ecEventProcessor.eventInfo = {
  24610. targetEl: el,
  24611. packedEvent: params,
  24612. model: model,
  24613. view: view
  24614. };
  24615. this.trigger(eveName, params);
  24616. }
  24617. };
  24618. // Consider that some component (like tooltip, brush, ...)
  24619. // register zr event handler, but user event handler might
  24620. // do anything, such as call `setOption` or `dispatchAction`,
  24621. // which probably update any of the content and probably
  24622. // cause problem if it is called previous other inner handlers.
  24623. handler.zrEventfulCallAtLast = true;
  24624. this._zr.on(eveName, handler, this);
  24625. }, this);
  24626. each(eventActionMap, function (actionType, eventType) {
  24627. this._messageCenter.on(eventType, function (event) {
  24628. this.trigger(eventType, event);
  24629. }, this);
  24630. }, this);
  24631. };
  24632. /**
  24633. * @return {boolean}
  24634. */
  24635. echartsProto.isDisposed = function () {
  24636. return this._disposed;
  24637. };
  24638. /**
  24639. * Clear
  24640. */
  24641. echartsProto.clear = function () {
  24642. this.setOption({ series: [] }, true);
  24643. };
  24644. /**
  24645. * Dispose instance
  24646. */
  24647. echartsProto.dispose = function () {
  24648. if (this._disposed) {
  24649. if (__DEV__) {
  24650. console.warn('Instance ' + this.id + ' has been disposed');
  24651. }
  24652. return;
  24653. }
  24654. this._disposed = true;
  24655. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  24656. var api = this._api;
  24657. var ecModel = this._model;
  24658. each(this._componentsViews, function (component) {
  24659. component.dispose(ecModel, api);
  24660. });
  24661. each(this._chartsViews, function (chart) {
  24662. chart.dispose(ecModel, api);
  24663. });
  24664. // Dispose after all views disposed
  24665. this._zr.dispose();
  24666. delete instances[this.id];
  24667. };
  24668. mixin(ECharts, Eventful);
  24669. function updateHoverLayerStatus(zr, ecModel) {
  24670. var storage = zr.storage;
  24671. var elCount = 0;
  24672. storage.traverse(function (el) {
  24673. if (!el.isGroup) {
  24674. elCount++;
  24675. }
  24676. });
  24677. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  24678. storage.traverse(function (el) {
  24679. if (!el.isGroup) {
  24680. // Don't switch back.
  24681. el.useHoverLayer = true;
  24682. }
  24683. });
  24684. }
  24685. }
  24686. /**
  24687. * Update chart progressive and blend.
  24688. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24689. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24690. */
  24691. function updateBlend(seriesModel, chartView) {
  24692. var blendMode = seriesModel.get('blendMode') || null;
  24693. if (__DEV__) {
  24694. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  24695. console.warn('Only canvas support blendMode');
  24696. }
  24697. }
  24698. chartView.group.traverse(function (el) {
  24699. // FIXME marker and other components
  24700. if (!el.isGroup) {
  24701. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  24702. if (el.style.blend !== blendMode) {
  24703. el.setStyle('blend', blendMode);
  24704. }
  24705. }
  24706. if (el.eachPendingDisplayable) {
  24707. el.eachPendingDisplayable(function (displayable) {
  24708. displayable.setStyle('blend', blendMode);
  24709. });
  24710. }
  24711. });
  24712. }
  24713. /**
  24714. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24715. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24716. */
  24717. function updateZ(model, view) {
  24718. var z = model.get('z');
  24719. var zlevel = model.get('zlevel');
  24720. // Set z and zlevel
  24721. view.group.traverse(function (el) {
  24722. if (el.type !== 'group') {
  24723. z != null && (el.z = z);
  24724. zlevel != null && (el.zlevel = zlevel);
  24725. }
  24726. });
  24727. }
  24728. function createExtensionAPI(ecInstance) {
  24729. var coordSysMgr = ecInstance._coordSysMgr;
  24730. return extend(new ExtensionAPI(ecInstance), {
  24731. // Inject methods
  24732. getCoordinateSystems: bind(
  24733. coordSysMgr.getCoordinateSystems, coordSysMgr
  24734. ),
  24735. getComponentByElement: function (el) {
  24736. while (el) {
  24737. var modelInfo = el.__ecComponentInfo;
  24738. if (modelInfo != null) {
  24739. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  24740. }
  24741. el = el.parent;
  24742. }
  24743. }
  24744. });
  24745. }
  24746. /**
  24747. * @class
  24748. * Usage of query:
  24749. * `chart.on('click', query, handler);`
  24750. * The `query` can be:
  24751. * + The component type query string, only `mainType` or `mainType.subType`,
  24752. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  24753. * + The component query object, like:
  24754. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  24755. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  24756. * + The data query object, like:
  24757. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  24758. * + The other query object (cmponent customized query), like:
  24759. * `{element: 'some'}` (only available in custom series).
  24760. *
  24761. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  24762. * same as there is no such prop in the `query` object.
  24763. */
  24764. function EventProcessor() {
  24765. // These info required: targetEl, packedEvent, model, view
  24766. this.eventInfo;
  24767. }
  24768. EventProcessor.prototype = {
  24769. constructor: EventProcessor,
  24770. normalizeQuery: function (query) {
  24771. var cptQuery = {};
  24772. var dataQuery = {};
  24773. var otherQuery = {};
  24774. // `query` is `mainType` or `mainType.subType` of component.
  24775. if (isString(query)) {
  24776. var condCptType = parseClassType(query);
  24777. // `.main` and `.sub` may be ''.
  24778. cptQuery.mainType = condCptType.main || null;
  24779. cptQuery.subType = condCptType.sub || null;
  24780. }
  24781. // `query` is an object, convert to {mainType, index, name, id}.
  24782. else {
  24783. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  24784. // can not be used in `compomentModel.filterForExposedEvent`.
  24785. var suffixes = ['Index', 'Name', 'Id'];
  24786. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  24787. each$1(query, function (val, key) {
  24788. var reserved = false;
  24789. for (var i = 0; i < suffixes.length; i++) {
  24790. var propSuffix = suffixes[i];
  24791. var suffixPos = key.lastIndexOf(propSuffix);
  24792. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  24793. var mainType = key.slice(0, suffixPos);
  24794. // Consider `dataIndex`.
  24795. if (mainType !== 'data') {
  24796. cptQuery.mainType = mainType;
  24797. cptQuery[propSuffix.toLowerCase()] = val;
  24798. reserved = true;
  24799. }
  24800. }
  24801. }
  24802. if (dataKeys.hasOwnProperty(key)) {
  24803. dataQuery[key] = val;
  24804. reserved = true;
  24805. }
  24806. if (!reserved) {
  24807. otherQuery[key] = val;
  24808. }
  24809. });
  24810. }
  24811. return {
  24812. cptQuery: cptQuery,
  24813. dataQuery: dataQuery,
  24814. otherQuery: otherQuery
  24815. };
  24816. },
  24817. filter: function (eventType, query, args) {
  24818. // They should be assigned before each trigger call.
  24819. var eventInfo = this.eventInfo;
  24820. if (!eventInfo) {
  24821. return true;
  24822. }
  24823. var targetEl = eventInfo.targetEl;
  24824. var packedEvent = eventInfo.packedEvent;
  24825. var model = eventInfo.model;
  24826. var view = eventInfo.view;
  24827. // For event like 'globalout'.
  24828. if (!model || !view) {
  24829. return true;
  24830. }
  24831. var cptQuery = query.cptQuery;
  24832. var dataQuery = query.dataQuery;
  24833. return check(cptQuery, model, 'mainType')
  24834. && check(cptQuery, model, 'subType')
  24835. && check(cptQuery, model, 'index', 'componentIndex')
  24836. && check(cptQuery, model, 'name')
  24837. && check(cptQuery, model, 'id')
  24838. && check(dataQuery, packedEvent, 'name')
  24839. && check(dataQuery, packedEvent, 'dataIndex')
  24840. && check(dataQuery, packedEvent, 'dataType')
  24841. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  24842. eventType, query.otherQuery, targetEl, packedEvent
  24843. ));
  24844. function check(query, host, prop, propOnHost) {
  24845. return query[prop] == null || host[propOnHost || prop] === query[prop];
  24846. }
  24847. },
  24848. afterTrigger: function () {
  24849. // Make sure the eventInfo wont be used in next trigger.
  24850. this.eventInfo = null;
  24851. }
  24852. };
  24853. /**
  24854. * @type {Object} key: actionType.
  24855. * @inner
  24856. */
  24857. var actions = {};
  24858. /**
  24859. * Map eventType to actionType
  24860. * @type {Object}
  24861. */
  24862. var eventActionMap = {};
  24863. /**
  24864. * Data processor functions of each stage
  24865. * @type {Array.<Object.<string, Function>>}
  24866. * @inner
  24867. */
  24868. var dataProcessorFuncs = [];
  24869. /**
  24870. * @type {Array.<Function>}
  24871. * @inner
  24872. */
  24873. var optionPreprocessorFuncs = [];
  24874. /**
  24875. * @type {Array.<Function>}
  24876. * @inner
  24877. */
  24878. var postUpdateFuncs = [];
  24879. /**
  24880. * Visual encoding functions of each stage
  24881. * @type {Array.<Object.<string, Function>>}
  24882. */
  24883. var visualFuncs = [];
  24884. /**
  24885. * Theme storage
  24886. * @type {Object.<key, Object>}
  24887. */
  24888. var themeStorage = {};
  24889. /**
  24890. * Loading effects
  24891. */
  24892. var loadingEffects = {};
  24893. var instances = {};
  24894. var connectedGroups = {};
  24895. var idBase = new Date() - 0;
  24896. var groupIdBase = new Date() - 0;
  24897. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  24898. function enableConnect(chart) {
  24899. var STATUS_PENDING = 0;
  24900. var STATUS_UPDATING = 1;
  24901. var STATUS_UPDATED = 2;
  24902. var STATUS_KEY = '__connectUpdateStatus';
  24903. function updateConnectedChartsStatus(charts, status) {
  24904. for (var i = 0; i < charts.length; i++) {
  24905. var otherChart = charts[i];
  24906. otherChart[STATUS_KEY] = status;
  24907. }
  24908. }
  24909. each(eventActionMap, function (actionType, eventType) {
  24910. chart._messageCenter.on(eventType, function (event) {
  24911. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  24912. if (event && event.escapeConnect) {
  24913. return;
  24914. }
  24915. var action = chart.makeActionFromEvent(event);
  24916. var otherCharts = [];
  24917. each(instances, function (otherChart) {
  24918. if (otherChart !== chart && otherChart.group === chart.group) {
  24919. otherCharts.push(otherChart);
  24920. }
  24921. });
  24922. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  24923. each(otherCharts, function (otherChart) {
  24924. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  24925. otherChart.dispatchAction(action);
  24926. }
  24927. });
  24928. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  24929. }
  24930. });
  24931. });
  24932. }
  24933. /**
  24934. * @param {HTMLElement} dom
  24935. * @param {Object} [theme]
  24936. * @param {Object} opts
  24937. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  24938. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  24939. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  24940. * Can be 'auto' (the same as null/undefined)
  24941. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  24942. * Can be 'auto' (the same as null/undefined)
  24943. */
  24944. function init(dom, theme$$1, opts) {
  24945. if (__DEV__) {
  24946. // Check version
  24947. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  24948. throw new Error(
  24949. 'zrender/src ' + version$1
  24950. + ' is too old for ECharts ' + version
  24951. + '. Current version need ZRender '
  24952. + dependencies.zrender + '+'
  24953. );
  24954. }
  24955. if (!dom) {
  24956. throw new Error('Initialize failed: invalid dom.');
  24957. }
  24958. }
  24959. var existInstance = getInstanceByDom(dom);
  24960. if (existInstance) {
  24961. if (__DEV__) {
  24962. console.warn('There is a chart instance already initialized on the dom.');
  24963. }
  24964. return existInstance;
  24965. }
  24966. if (__DEV__) {
  24967. if (isDom(dom)
  24968. && dom.nodeName.toUpperCase() !== 'CANVAS'
  24969. && (
  24970. (!dom.clientWidth && (!opts || opts.width == null))
  24971. || (!dom.clientHeight && (!opts || opts.height == null))
  24972. )
  24973. ) {
  24974. console.warn('Can\'t get dom width or height');
  24975. }
  24976. }
  24977. var chart = new ECharts(dom, theme$$1, opts);
  24978. chart.id = 'ec_' + idBase++;
  24979. instances[chart.id] = chart;
  24980. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  24981. enableConnect(chart);
  24982. return chart;
  24983. }
  24984. /**
  24985. * @return {string|Array.<module:echarts~ECharts>} groupId
  24986. */
  24987. function connect(groupId) {
  24988. // Is array of charts
  24989. if (isArray(groupId)) {
  24990. var charts = groupId;
  24991. groupId = null;
  24992. // If any chart has group
  24993. each(charts, function (chart) {
  24994. if (chart.group != null) {
  24995. groupId = chart.group;
  24996. }
  24997. });
  24998. groupId = groupId || ('g_' + groupIdBase++);
  24999. each(charts, function (chart) {
  25000. chart.group = groupId;
  25001. });
  25002. }
  25003. connectedGroups[groupId] = true;
  25004. return groupId;
  25005. }
  25006. /**
  25007. * @DEPRECATED
  25008. * @return {string} groupId
  25009. */
  25010. function disConnect(groupId) {
  25011. connectedGroups[groupId] = false;
  25012. }
  25013. /**
  25014. * @return {string} groupId
  25015. */
  25016. var disconnect = disConnect;
  25017. /**
  25018. * Dispose a chart instance
  25019. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  25020. */
  25021. function dispose(chart) {
  25022. if (typeof chart === 'string') {
  25023. chart = instances[chart];
  25024. }
  25025. else if (!(chart instanceof ECharts)) {
  25026. // Try to treat as dom
  25027. chart = getInstanceByDom(chart);
  25028. }
  25029. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  25030. chart.dispose();
  25031. }
  25032. }
  25033. /**
  25034. * @param {HTMLElement} dom
  25035. * @return {echarts~ECharts}
  25036. */
  25037. function getInstanceByDom(dom) {
  25038. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  25039. }
  25040. /**
  25041. * @param {string} key
  25042. * @return {echarts~ECharts}
  25043. */
  25044. function getInstanceById(key) {
  25045. return instances[key];
  25046. }
  25047. /**
  25048. * Register theme
  25049. */
  25050. function registerTheme(name, theme$$1) {
  25051. themeStorage[name] = theme$$1;
  25052. }
  25053. /**
  25054. * Register option preprocessor
  25055. * @param {Function} preprocessorFunc
  25056. */
  25057. function registerPreprocessor(preprocessorFunc) {
  25058. optionPreprocessorFuncs.push(preprocessorFunc);
  25059. }
  25060. /**
  25061. * @param {number} [priority=1000]
  25062. * @param {Object|Function} processor
  25063. */
  25064. function registerProcessor(priority, processor) {
  25065. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  25066. }
  25067. /**
  25068. * Register postUpdater
  25069. * @param {Function} postUpdateFunc
  25070. */
  25071. function registerPostUpdate(postUpdateFunc) {
  25072. postUpdateFuncs.push(postUpdateFunc);
  25073. }
  25074. /**
  25075. * Usage:
  25076. * registerAction('someAction', 'someEvent', function () { ... });
  25077. * registerAction('someAction', function () { ... });
  25078. * registerAction(
  25079. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  25080. * function () { ... }
  25081. * );
  25082. *
  25083. * @param {(string|Object)} actionInfo
  25084. * @param {string} actionInfo.type
  25085. * @param {string} [actionInfo.event]
  25086. * @param {string} [actionInfo.update]
  25087. * @param {string} [eventName]
  25088. * @param {Function} action
  25089. */
  25090. function registerAction(actionInfo, eventName, action) {
  25091. if (typeof eventName === 'function') {
  25092. action = eventName;
  25093. eventName = '';
  25094. }
  25095. var actionType = isObject(actionInfo)
  25096. ? actionInfo.type
  25097. : ([actionInfo, actionInfo = {
  25098. event: eventName
  25099. }][0]);
  25100. // Event name is all lowercase
  25101. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  25102. eventName = actionInfo.event;
  25103. // Validate action type and event name.
  25104. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  25105. if (!actions[actionType]) {
  25106. actions[actionType] = {action: action, actionInfo: actionInfo};
  25107. }
  25108. eventActionMap[eventName] = actionType;
  25109. }
  25110. /**
  25111. * @param {string} type
  25112. * @param {*} CoordinateSystem
  25113. */
  25114. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  25115. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  25116. }
  25117. /**
  25118. * Get dimensions of specified coordinate system.
  25119. * @param {string} type
  25120. * @return {Array.<string|Object>}
  25121. */
  25122. function getCoordinateSystemDimensions(type) {
  25123. var coordSysCreator = CoordinateSystemManager.get(type);
  25124. if (coordSysCreator) {
  25125. return coordSysCreator.getDimensionsInfo
  25126. ? coordSysCreator.getDimensionsInfo()
  25127. : coordSysCreator.dimensions.slice();
  25128. }
  25129. }
  25130. /**
  25131. * Layout is a special stage of visual encoding
  25132. * Most visual encoding like color are common for different chart
  25133. * But each chart has it's own layout algorithm
  25134. *
  25135. * @param {number} [priority=1000]
  25136. * @param {Function} layoutTask
  25137. */
  25138. function registerLayout(priority, layoutTask) {
  25139. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  25140. }
  25141. /**
  25142. * @param {number} [priority=3000]
  25143. * @param {module:echarts/stream/Task} visualTask
  25144. */
  25145. function registerVisual(priority, visualTask) {
  25146. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  25147. }
  25148. /**
  25149. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  25150. */
  25151. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  25152. if (isFunction(priority) || isObject(priority)) {
  25153. fn = priority;
  25154. priority = defaultPriority;
  25155. }
  25156. if (__DEV__) {
  25157. if (isNaN(priority) || priority == null) {
  25158. throw new Error('Illegal priority');
  25159. }
  25160. // Check duplicate
  25161. each(targetList, function (wrap) {
  25162. assert(wrap.__raw !== fn);
  25163. });
  25164. }
  25165. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  25166. stageHandler.__prio = priority;
  25167. stageHandler.__raw = fn;
  25168. targetList.push(stageHandler);
  25169. return stageHandler;
  25170. }
  25171. /**
  25172. * @param {string} name
  25173. */
  25174. function registerLoading(name, loadingFx) {
  25175. loadingEffects[name] = loadingFx;
  25176. }
  25177. /**
  25178. * @param {Object} opts
  25179. * @param {string} [superClass]
  25180. */
  25181. function extendComponentModel(opts/*, superClass*/) {
  25182. // var Clazz = ComponentModel;
  25183. // if (superClass) {
  25184. // var classType = parseClassType(superClass);
  25185. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25186. // }
  25187. return ComponentModel.extend(opts);
  25188. }
  25189. /**
  25190. * @param {Object} opts
  25191. * @param {string} [superClass]
  25192. */
  25193. function extendComponentView(opts/*, superClass*/) {
  25194. // var Clazz = ComponentView;
  25195. // if (superClass) {
  25196. // var classType = parseClassType(superClass);
  25197. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  25198. // }
  25199. return Component.extend(opts);
  25200. }
  25201. /**
  25202. * @param {Object} opts
  25203. * @param {string} [superClass]
  25204. */
  25205. function extendSeriesModel(opts/*, superClass*/) {
  25206. // var Clazz = SeriesModel;
  25207. // if (superClass) {
  25208. // superClass = 'series.' + superClass.replace('series.', '');
  25209. // var classType = parseClassType(superClass);
  25210. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25211. // }
  25212. return SeriesModel.extend(opts);
  25213. }
  25214. /**
  25215. * @param {Object} opts
  25216. * @param {string} [superClass]
  25217. */
  25218. function extendChartView(opts/*, superClass*/) {
  25219. // var Clazz = ChartView;
  25220. // if (superClass) {
  25221. // superClass = superClass.replace('series.', '');
  25222. // var classType = parseClassType(superClass);
  25223. // Clazz = ChartView.getClass(classType.main, true);
  25224. // }
  25225. return Chart.extend(opts);
  25226. }
  25227. /**
  25228. * ZRender need a canvas context to do measureText.
  25229. * But in node environment canvas may be created by node-canvas.
  25230. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  25231. *
  25232. * Be careful of using it in the browser.
  25233. *
  25234. * @param {Function} creator
  25235. * @example
  25236. * var Canvas = require('canvas');
  25237. * var echarts = require('echarts');
  25238. * echarts.setCanvasCreator(function () {
  25239. * // Small size is enough.
  25240. * return new Canvas(32, 32);
  25241. * });
  25242. */
  25243. function setCanvasCreator(creator) {
  25244. $override('createCanvas', creator);
  25245. }
  25246. /**
  25247. * @param {string} mapName
  25248. * @param {Array.<Object>|Object|string} geoJson
  25249. * @param {Object} [specialAreas]
  25250. *
  25251. * @example GeoJSON
  25252. * $.get('USA.json', function (geoJson) {
  25253. * echarts.registerMap('USA', geoJson);
  25254. * // Or
  25255. * echarts.registerMap('USA', {
  25256. * geoJson: geoJson,
  25257. * specialAreas: {}
  25258. * })
  25259. * });
  25260. *
  25261. * $.get('airport.svg', function (svg) {
  25262. * echarts.registerMap('airport', {
  25263. * svg: svg
  25264. * }
  25265. * });
  25266. *
  25267. * echarts.registerMap('eu', [
  25268. * {svg: eu-topographic.svg},
  25269. * {geoJSON: eu.json}
  25270. * ])
  25271. */
  25272. function registerMap(mapName, geoJson, specialAreas) {
  25273. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  25274. }
  25275. /**
  25276. * @param {string} mapName
  25277. * @return {Object}
  25278. */
  25279. function getMap(mapName) {
  25280. // For backward compatibility, only return the first one.
  25281. var records = mapDataStorage.retrieveMap(mapName);
  25282. return records && records[0] && {
  25283. geoJson: records[0].geoJSON,
  25284. specialAreas: records[0].specialAreas
  25285. };
  25286. }
  25287. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  25288. registerPreprocessor(backwardCompat);
  25289. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  25290. registerLoading('default', loadingDefault);
  25291. // Default actions
  25292. registerAction({
  25293. type: 'highlight',
  25294. event: 'highlight',
  25295. update: 'highlight'
  25296. }, noop);
  25297. registerAction({
  25298. type: 'downplay',
  25299. event: 'downplay',
  25300. update: 'downplay'
  25301. }, noop);
  25302. // Default theme
  25303. registerTheme('light', lightTheme);
  25304. registerTheme('dark', theme);
  25305. // For backward compatibility, where the namespace `dataTool` will
  25306. // be mounted on `echarts` is the extension `dataTool` is imported.
  25307. var dataTool = {};
  25308. /*
  25309. * Licensed to the Apache Software Foundation (ASF) under one
  25310. * or more contributor license agreements. See the NOTICE file
  25311. * distributed with this work for additional information
  25312. * regarding copyright ownership. The ASF licenses this file
  25313. * to you under the Apache License, Version 2.0 (the
  25314. * "License"); you may not use this file except in compliance
  25315. * with the License. You may obtain a copy of the License at
  25316. *
  25317. * http://www.apache.org/licenses/LICENSE-2.0
  25318. *
  25319. * Unless required by applicable law or agreed to in writing,
  25320. * software distributed under the License is distributed on an
  25321. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25322. * KIND, either express or implied. See the License for the
  25323. * specific language governing permissions and limitations
  25324. * under the License.
  25325. */
  25326. function defaultKeyGetter(item) {
  25327. return item;
  25328. }
  25329. /**
  25330. * @param {Array} oldArr
  25331. * @param {Array} newArr
  25332. * @param {Function} oldKeyGetter
  25333. * @param {Function} newKeyGetter
  25334. * @param {Object} [context] Can be visited by this.context in callback.
  25335. */
  25336. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  25337. this._old = oldArr;
  25338. this._new = newArr;
  25339. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  25340. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  25341. this.context = context;
  25342. }
  25343. DataDiffer.prototype = {
  25344. constructor: DataDiffer,
  25345. /**
  25346. * Callback function when add a data
  25347. */
  25348. add: function (func) {
  25349. this._add = func;
  25350. return this;
  25351. },
  25352. /**
  25353. * Callback function when update a data
  25354. */
  25355. update: function (func) {
  25356. this._update = func;
  25357. return this;
  25358. },
  25359. /**
  25360. * Callback function when remove a data
  25361. */
  25362. remove: function (func) {
  25363. this._remove = func;
  25364. return this;
  25365. },
  25366. execute: function () {
  25367. var oldArr = this._old;
  25368. var newArr = this._new;
  25369. var oldDataIndexMap = {};
  25370. var newDataIndexMap = {};
  25371. var oldDataKeyArr = [];
  25372. var newDataKeyArr = [];
  25373. var i;
  25374. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  25375. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  25376. // Travel by inverted order to make sure order consistency
  25377. // when duplicate keys exists (consider newDataIndex.pop() below).
  25378. // For performance consideration, these code below do not look neat.
  25379. for (i = 0; i < oldArr.length; i++) {
  25380. var key = oldDataKeyArr[i];
  25381. var idx = newDataIndexMap[key];
  25382. // idx can never be empty array here. see 'set null' logic below.
  25383. if (idx != null) {
  25384. // Consider there is duplicate key (for example, use dataItem.name as key).
  25385. // We should make sure every item in newArr and oldArr can be visited.
  25386. var len = idx.length;
  25387. if (len) {
  25388. len === 1 && (newDataIndexMap[key] = null);
  25389. idx = idx.unshift();
  25390. }
  25391. else {
  25392. newDataIndexMap[key] = null;
  25393. }
  25394. this._update && this._update(idx, i);
  25395. }
  25396. else {
  25397. this._remove && this._remove(i);
  25398. }
  25399. }
  25400. for (var i = 0; i < newDataKeyArr.length; i++) {
  25401. var key = newDataKeyArr[i];
  25402. if (newDataIndexMap.hasOwnProperty(key)) {
  25403. var idx = newDataIndexMap[key];
  25404. if (idx == null) {
  25405. continue;
  25406. }
  25407. // idx can never be empty array here. see 'set null' logic above.
  25408. if (!idx.length) {
  25409. this._add && this._add(idx);
  25410. }
  25411. else {
  25412. for (var j = 0, len = idx.length; j < len; j++) {
  25413. this._add && this._add(idx[j]);
  25414. }
  25415. }
  25416. }
  25417. }
  25418. }
  25419. };
  25420. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  25421. for (var i = 0; i < arr.length; i++) {
  25422. // Add prefix to avoid conflict with Object.prototype.
  25423. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  25424. var existence = map[key];
  25425. if (existence == null) {
  25426. keyArr.push(key);
  25427. map[key] = i;
  25428. }
  25429. else {
  25430. if (!existence.length) {
  25431. map[key] = existence = [existence];
  25432. }
  25433. existence.push(i);
  25434. }
  25435. }
  25436. }
  25437. /*
  25438. * Licensed to the Apache Software Foundation (ASF) under one
  25439. * or more contributor license agreements. See the NOTICE file
  25440. * distributed with this work for additional information
  25441. * regarding copyright ownership. The ASF licenses this file
  25442. * to you under the Apache License, Version 2.0 (the
  25443. * "License"); you may not use this file except in compliance
  25444. * with the License. You may obtain a copy of the License at
  25445. *
  25446. * http://www.apache.org/licenses/LICENSE-2.0
  25447. *
  25448. * Unless required by applicable law or agreed to in writing,
  25449. * software distributed under the License is distributed on an
  25450. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25451. * KIND, either express or implied. See the License for the
  25452. * specific language governing permissions and limitations
  25453. * under the License.
  25454. */
  25455. var OTHER_DIMENSIONS = createHashMap([
  25456. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  25457. ]);
  25458. function summarizeDimensions(data) {
  25459. var summary = {};
  25460. var encode = summary.encode = {};
  25461. var notExtraCoordDimMap = createHashMap();
  25462. var defaultedLabel = [];
  25463. var defaultedTooltip = [];
  25464. each$1(data.dimensions, function (dimName) {
  25465. var dimItem = data.getDimensionInfo(dimName);
  25466. var coordDim = dimItem.coordDim;
  25467. if (coordDim) {
  25468. if (__DEV__) {
  25469. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  25470. }
  25471. var coordDimArr = encode[coordDim];
  25472. if (!encode.hasOwnProperty(coordDim)) {
  25473. coordDimArr = encode[coordDim] = [];
  25474. }
  25475. coordDimArr[dimItem.coordDimIndex] = dimName;
  25476. if (!dimItem.isExtraCoord) {
  25477. notExtraCoordDimMap.set(coordDim, 1);
  25478. // Use the last coord dim (and label friendly) as default label,
  25479. // because when dataset is used, it is hard to guess which dimension
  25480. // can be value dimension. If both show x, y on label is not look good,
  25481. // and conventionally y axis is focused more.
  25482. if (mayLabelDimType(dimItem.type)) {
  25483. defaultedLabel[0] = dimName;
  25484. }
  25485. }
  25486. if (dimItem.defaultTooltip) {
  25487. defaultedTooltip.push(dimName);
  25488. }
  25489. }
  25490. OTHER_DIMENSIONS.each(function (v, otherDim) {
  25491. var otherDimArr = encode[otherDim];
  25492. if (!encode.hasOwnProperty(otherDim)) {
  25493. otherDimArr = encode[otherDim] = [];
  25494. }
  25495. var dimIndex = dimItem.otherDims[otherDim];
  25496. if (dimIndex != null && dimIndex !== false) {
  25497. otherDimArr[dimIndex] = dimItem.name;
  25498. }
  25499. });
  25500. });
  25501. var dataDimsOnCoord = [];
  25502. var encodeFirstDimNotExtra = {};
  25503. notExtraCoordDimMap.each(function (v, coordDim) {
  25504. var dimArr = encode[coordDim];
  25505. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  25506. // But should fix the case that radar axes: simplify the logic
  25507. // of `completeDimension`, remove `extraPrefix`.
  25508. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  25509. // Not necessary to remove duplicate, because a data
  25510. // dim canot on more than one coordDim.
  25511. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  25512. });
  25513. summary.dataDimsOnCoord = dataDimsOnCoord;
  25514. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  25515. var encodeLabel = encode.label;
  25516. // FIXME `encode.label` is not recommanded, because formatter can not be set
  25517. // in this way. Use label.formatter instead. May be remove this approach someday.
  25518. if (encodeLabel && encodeLabel.length) {
  25519. defaultedLabel = encodeLabel.slice();
  25520. }
  25521. var encodeTooltip = encode.tooltip;
  25522. if (encodeTooltip && encodeTooltip.length) {
  25523. defaultedTooltip = encodeTooltip.slice();
  25524. }
  25525. else if (!defaultedTooltip.length) {
  25526. defaultedTooltip = defaultedLabel.slice();
  25527. }
  25528. encode.defaultedLabel = defaultedLabel;
  25529. encode.defaultedTooltip = defaultedTooltip;
  25530. return summary;
  25531. }
  25532. function getDimensionTypeByAxis(axisType) {
  25533. return axisType === 'category'
  25534. ? 'ordinal'
  25535. : axisType === 'time'
  25536. ? 'time'
  25537. : 'float';
  25538. }
  25539. function mayLabelDimType(dimType) {
  25540. // In most cases, ordinal and time do not suitable for label.
  25541. // Ordinal info can be displayed on axis. Time is too long.
  25542. return !(dimType === 'ordinal' || dimType === 'time');
  25543. }
  25544. // function findTheLastDimMayLabel(data) {
  25545. // // Get last value dim
  25546. // var dimensions = data.dimensions.slice();
  25547. // var valueType;
  25548. // var valueDim;
  25549. // while (dimensions.length && (
  25550. // valueDim = dimensions.pop(),
  25551. // valueType = data.getDimensionInfo(valueDim).type,
  25552. // valueType === 'ordinal' || valueType === 'time'
  25553. // )) {} // jshint ignore:line
  25554. // return valueDim;
  25555. // }
  25556. /*
  25557. * Licensed to the Apache Software Foundation (ASF) under one
  25558. * or more contributor license agreements. See the NOTICE file
  25559. * distributed with this work for additional information
  25560. * regarding copyright ownership. The ASF licenses this file
  25561. * to you under the Apache License, Version 2.0 (the
  25562. * "License"); you may not use this file except in compliance
  25563. * with the License. You may obtain a copy of the License at
  25564. *
  25565. * http://www.apache.org/licenses/LICENSE-2.0
  25566. *
  25567. * Unless required by applicable law or agreed to in writing,
  25568. * software distributed under the License is distributed on an
  25569. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25570. * KIND, either express or implied. See the License for the
  25571. * specific language governing permissions and limitations
  25572. * under the License.
  25573. */
  25574. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  25575. /**
  25576. * List for data storage
  25577. * @module echarts/data/List
  25578. */
  25579. var isObject$4 = isObject$1;
  25580. var UNDEFINED = 'undefined';
  25581. var INDEX_NOT_FOUND = -1;
  25582. // Use prefix to avoid index to be the same as otherIdList[idx],
  25583. // which will cause weird udpate animation.
  25584. var ID_PREFIX = 'e\0\0';
  25585. var dataCtors = {
  25586. 'float': typeof Float64Array === UNDEFINED
  25587. ? Array : Float64Array,
  25588. 'int': typeof Int32Array === UNDEFINED
  25589. ? Array : Int32Array,
  25590. // Ordinal data type can be string or int
  25591. 'ordinal': Array,
  25592. 'number': Array,
  25593. 'time': Array
  25594. };
  25595. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  25596. // different from the Ctor of typed array.
  25597. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  25598. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  25599. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  25600. function getIndicesCtor(list) {
  25601. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  25602. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  25603. }
  25604. function cloneChunk(originalChunk) {
  25605. var Ctor = originalChunk.constructor;
  25606. // Only shallow clone is enough when Array.
  25607. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  25608. }
  25609. var TRANSFERABLE_PROPERTIES = [
  25610. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  25611. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  25612. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  25613. ];
  25614. var CLONE_PROPERTIES = [
  25615. '_extent', '_approximateExtent', '_rawExtent'
  25616. ];
  25617. function transferProperties(target, source) {
  25618. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  25619. if (source.hasOwnProperty(propName)) {
  25620. target[propName] = source[propName];
  25621. }
  25622. });
  25623. target.__wrappedMethods = source.__wrappedMethods;
  25624. each$1(CLONE_PROPERTIES, function (propName) {
  25625. target[propName] = clone(source[propName]);
  25626. });
  25627. target._calculationInfo = extend(source._calculationInfo);
  25628. }
  25629. /**
  25630. * @constructor
  25631. * @alias module:echarts/data/List
  25632. *
  25633. * @param {Array.<string|Object>} dimensions
  25634. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  25635. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  25636. * Spetial fields: {
  25637. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  25638. * createInvertedIndices: <boolean>
  25639. * }
  25640. * @param {module:echarts/model/Model} hostModel
  25641. */
  25642. var List = function (dimensions, hostModel) {
  25643. dimensions = dimensions || ['x', 'y'];
  25644. var dimensionInfos = {};
  25645. var dimensionNames = [];
  25646. var invertedIndicesMap = {};
  25647. for (var i = 0; i < dimensions.length; i++) {
  25648. // Use the original dimensions[i], where other flag props may exists.
  25649. var dimensionInfo = dimensions[i];
  25650. if (isString(dimensionInfo)) {
  25651. dimensionInfo = {name: dimensionInfo};
  25652. }
  25653. var dimensionName = dimensionInfo.name;
  25654. dimensionInfo.type = dimensionInfo.type || 'float';
  25655. if (!dimensionInfo.coordDim) {
  25656. dimensionInfo.coordDim = dimensionName;
  25657. dimensionInfo.coordDimIndex = 0;
  25658. }
  25659. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  25660. dimensionNames.push(dimensionName);
  25661. dimensionInfos[dimensionName] = dimensionInfo;
  25662. dimensionInfo.index = i;
  25663. if (dimensionInfo.createInvertedIndices) {
  25664. invertedIndicesMap[dimensionName] = [];
  25665. }
  25666. }
  25667. /**
  25668. * @readOnly
  25669. * @type {Array.<string>}
  25670. */
  25671. this.dimensions = dimensionNames;
  25672. /**
  25673. * Infomation of each data dimension, like data type.
  25674. * @type {Object}
  25675. */
  25676. this._dimensionInfos = dimensionInfos;
  25677. /**
  25678. * @type {module:echarts/model/Model}
  25679. */
  25680. this.hostModel = hostModel;
  25681. /**
  25682. * @type {module:echarts/model/Model}
  25683. */
  25684. this.dataType;
  25685. /**
  25686. * Indices stores the indices of data subset after filtered.
  25687. * This data subset will be used in chart.
  25688. * @type {Array.<number>}
  25689. * @readOnly
  25690. */
  25691. this._indices = null;
  25692. this._count = 0;
  25693. this._rawCount = 0;
  25694. /**
  25695. * Data storage
  25696. * @type {Object.<key, Array.<TypedArray|Array>>}
  25697. * @private
  25698. */
  25699. this._storage = {};
  25700. /**
  25701. * @type {Array.<string>}
  25702. */
  25703. this._nameList = [];
  25704. /**
  25705. * @type {Array.<string>}
  25706. */
  25707. this._idList = [];
  25708. /**
  25709. * Models of data option is stored sparse for optimizing memory cost
  25710. * @type {Array.<module:echarts/model/Model>}
  25711. * @private
  25712. */
  25713. this._optionModels = [];
  25714. /**
  25715. * Global visual properties after visual coding
  25716. * @type {Object}
  25717. * @private
  25718. */
  25719. this._visual = {};
  25720. /**
  25721. * Globel layout properties.
  25722. * @type {Object}
  25723. * @private
  25724. */
  25725. this._layout = {};
  25726. /**
  25727. * Item visual properties after visual coding
  25728. * @type {Array.<Object>}
  25729. * @private
  25730. */
  25731. this._itemVisuals = [];
  25732. /**
  25733. * Key: visual type, Value: boolean
  25734. * @type {Object}
  25735. * @readOnly
  25736. */
  25737. this.hasItemVisual = {};
  25738. /**
  25739. * Item layout properties after layout
  25740. * @type {Array.<Object>}
  25741. * @private
  25742. */
  25743. this._itemLayouts = [];
  25744. /**
  25745. * Graphic elemnents
  25746. * @type {Array.<module:zrender/Element>}
  25747. * @private
  25748. */
  25749. this._graphicEls = [];
  25750. /**
  25751. * Max size of each chunk.
  25752. * @type {number}
  25753. * @private
  25754. */
  25755. this._chunkSize = 1e5;
  25756. /**
  25757. * @type {number}
  25758. * @private
  25759. */
  25760. this._chunkCount = 0;
  25761. /**
  25762. * @type {Array.<Array|Object>}
  25763. * @private
  25764. */
  25765. this._rawData;
  25766. /**
  25767. * Raw extent will not be cloned, but only transfered.
  25768. * It will not be calculated util needed.
  25769. * key: dim,
  25770. * value: {end: number, extent: Array.<number>}
  25771. * @type {Object}
  25772. * @private
  25773. */
  25774. this._rawExtent = {};
  25775. /**
  25776. * @type {Object}
  25777. * @private
  25778. */
  25779. this._extent = {};
  25780. /**
  25781. * key: dim
  25782. * value: extent
  25783. * @type {Object}
  25784. * @private
  25785. */
  25786. this._approximateExtent = {};
  25787. /**
  25788. * Cache summary info for fast visit. See "dimensionHelper".
  25789. * @type {Object}
  25790. * @private
  25791. */
  25792. this._dimensionsSummary = summarizeDimensions(this);
  25793. /**
  25794. * @type {Object.<Array|TypedArray>}
  25795. * @private
  25796. */
  25797. this._invertedIndicesMap = invertedIndicesMap;
  25798. /**
  25799. * @type {Object}
  25800. * @private
  25801. */
  25802. this._calculationInfo = {};
  25803. };
  25804. var listProto = List.prototype;
  25805. listProto.type = 'list';
  25806. /**
  25807. * If each data item has it's own option
  25808. * @type {boolean}
  25809. */
  25810. listProto.hasItemOption = true;
  25811. /**
  25812. * Get dimension name
  25813. * @param {string|number} dim
  25814. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  25815. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  25816. * @return {string} Concrete dim name.
  25817. */
  25818. listProto.getDimension = function (dim) {
  25819. if (!isNaN(dim)) {
  25820. dim = this.dimensions[dim] || dim;
  25821. }
  25822. return dim;
  25823. };
  25824. /**
  25825. * Get type and calculation info of particular dimension
  25826. * @param {string|number} dim
  25827. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  25828. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  25829. */
  25830. listProto.getDimensionInfo = function (dim) {
  25831. // Do not clone, because there may be categories in dimInfo.
  25832. return this._dimensionInfos[this.getDimension(dim)];
  25833. };
  25834. /**
  25835. * @return {Array.<string>} concrete dimension name list on coord.
  25836. */
  25837. listProto.getDimensionsOnCoord = function () {
  25838. return this._dimensionsSummary.dataDimsOnCoord.slice();
  25839. };
  25840. /**
  25841. * @param {string} coordDim
  25842. * @param {number} [idx] A coordDim may map to more than one data dim.
  25843. * If idx is `true`, return a array of all mapped dims.
  25844. * If idx is not specified, return the first dim not extra.
  25845. * @return {string|Array.<string>} concrete data dim.
  25846. * If idx is number, and not found, return null/undefined.
  25847. * If idx is `true`, and not found, return empty array (always return array).
  25848. */
  25849. listProto.mapDimension = function (coordDim, idx) {
  25850. var dimensionsSummary = this._dimensionsSummary;
  25851. if (idx == null) {
  25852. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  25853. }
  25854. var dims = dimensionsSummary.encode[coordDim];
  25855. return idx === true
  25856. // always return array if idx is `true`
  25857. ? (dims || []).slice()
  25858. : (dims && dims[idx]);
  25859. };
  25860. /**
  25861. * Initialize from data
  25862. * @param {Array.<Object|number|Array>} data source or data or data provider.
  25863. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  25864. * defualt label/tooltip.
  25865. * A name can be specified in encode.itemName,
  25866. * or dataItem.name (only for series option data),
  25867. * or provided in nameList from outside.
  25868. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  25869. */
  25870. listProto.initData = function (data, nameList, dimValueGetter) {
  25871. var notProvider = Source.isInstance(data) || isArrayLike(data);
  25872. if (notProvider) {
  25873. data = new DefaultDataProvider(data, this.dimensions.length);
  25874. }
  25875. if (__DEV__) {
  25876. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  25877. throw new Error('Inavlid data provider.');
  25878. }
  25879. }
  25880. this._rawData = data;
  25881. // Clear
  25882. this._storage = {};
  25883. this._indices = null;
  25884. this._nameList = nameList || [];
  25885. this._idList = [];
  25886. this._nameRepeatCount = {};
  25887. if (!dimValueGetter) {
  25888. this.hasItemOption = false;
  25889. }
  25890. /**
  25891. * @readOnly
  25892. */
  25893. this.defaultDimValueGetter = defaultDimValueGetters[
  25894. this._rawData.getSource().sourceFormat
  25895. ];
  25896. // Default dim value getter
  25897. this._dimValueGetter = dimValueGetter = dimValueGetter
  25898. || this.defaultDimValueGetter;
  25899. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  25900. // Reset raw extent.
  25901. this._rawExtent = {};
  25902. this._initDataFromProvider(0, data.count());
  25903. // If data has no item option.
  25904. if (data.pure) {
  25905. this.hasItemOption = false;
  25906. }
  25907. };
  25908. listProto.getProvider = function () {
  25909. return this._rawData;
  25910. };
  25911. /**
  25912. * Caution: Can be only called on raw data (before `this._indices` created).
  25913. */
  25914. listProto.appendData = function (data) {
  25915. if (__DEV__) {
  25916. assert$1(!this._indices, 'appendData can only be called on raw data.');
  25917. }
  25918. var rawData = this._rawData;
  25919. var start = this.count();
  25920. rawData.appendData(data);
  25921. var end = rawData.count();
  25922. if (!rawData.persistent) {
  25923. end += start;
  25924. }
  25925. this._initDataFromProvider(start, end);
  25926. };
  25927. /**
  25928. * Caution: Can be only called on raw data (before `this._indices` created).
  25929. * This method does not modify `rawData` (`dataProvider`), but only
  25930. * add values to storage.
  25931. *
  25932. * The final count will be increased by `Math.max(values.length, names.length)`.
  25933. *
  25934. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  25935. * [
  25936. * [12, 33, 44],
  25937. * [NaN, 43, 1],
  25938. * ['-', 'asdf', 0]
  25939. * ]
  25940. * Each item is exaclty cooresponding to a dimension.
  25941. * @param {Array.<string>} [names]
  25942. */
  25943. listProto.appendValues = function (values, names) {
  25944. var chunkSize = this._chunkSize;
  25945. var storage = this._storage;
  25946. var dimensions = this.dimensions;
  25947. var dimLen = dimensions.length;
  25948. var rawExtent = this._rawExtent;
  25949. var start = this.count();
  25950. var end = start + Math.max(values.length, names ? names.length : 0);
  25951. var originalChunkCount = this._chunkCount;
  25952. for (var i = 0; i < dimLen; i++) {
  25953. var dim = dimensions[i];
  25954. if (!rawExtent[dim]) {
  25955. rawExtent[dim] = getInitialExtent();
  25956. }
  25957. if (!storage[dim]) {
  25958. storage[dim] = [];
  25959. }
  25960. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  25961. this._chunkCount = storage[dim].length;
  25962. }
  25963. var emptyDataItem = new Array(dimLen);
  25964. for (var idx = start; idx < end; idx++) {
  25965. var sourceIdx = idx - start;
  25966. var chunkIndex = Math.floor(idx / chunkSize);
  25967. var chunkOffset = idx % chunkSize;
  25968. // Store the data by dimensions
  25969. for (var k = 0; k < dimLen; k++) {
  25970. var dim = dimensions[k];
  25971. var val = this._dimValueGetterArrayRows(
  25972. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  25973. );
  25974. storage[dim][chunkIndex][chunkOffset] = val;
  25975. var dimRawExtent = rawExtent[dim];
  25976. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  25977. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  25978. }
  25979. if (names) {
  25980. this._nameList[idx] = names[sourceIdx];
  25981. }
  25982. }
  25983. this._rawCount = this._count = end;
  25984. // Reset data extent
  25985. this._extent = {};
  25986. prepareInvertedIndex(this);
  25987. };
  25988. listProto._initDataFromProvider = function (start, end) {
  25989. // Optimize.
  25990. if (start >= end) {
  25991. return;
  25992. }
  25993. var chunkSize = this._chunkSize;
  25994. var rawData = this._rawData;
  25995. var storage = this._storage;
  25996. var dimensions = this.dimensions;
  25997. var dimLen = dimensions.length;
  25998. var dimensionInfoMap = this._dimensionInfos;
  25999. var nameList = this._nameList;
  26000. var idList = this._idList;
  26001. var rawExtent = this._rawExtent;
  26002. var nameRepeatCount = this._nameRepeatCount = {};
  26003. var nameDimIdx;
  26004. var originalChunkCount = this._chunkCount;
  26005. for (var i = 0; i < dimLen; i++) {
  26006. var dim = dimensions[i];
  26007. if (!rawExtent[dim]) {
  26008. rawExtent[dim] = getInitialExtent();
  26009. }
  26010. var dimInfo = dimensionInfoMap[dim];
  26011. if (dimInfo.otherDims.itemName === 0) {
  26012. nameDimIdx = this._nameDimIdx = i;
  26013. }
  26014. if (dimInfo.otherDims.itemId === 0) {
  26015. this._idDimIdx = i;
  26016. }
  26017. if (!storage[dim]) {
  26018. storage[dim] = [];
  26019. }
  26020. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  26021. this._chunkCount = storage[dim].length;
  26022. }
  26023. var dataItem = new Array(dimLen);
  26024. for (var idx = start; idx < end; idx++) {
  26025. // NOTICE: Try not to write things into dataItem
  26026. dataItem = rawData.getItem(idx, dataItem);
  26027. // Each data item is value
  26028. // [1, 2]
  26029. // 2
  26030. // Bar chart, line chart which uses category axis
  26031. // only gives the 'y' value. 'x' value is the indices of category
  26032. // Use a tempValue to normalize the value to be a (x, y) value
  26033. var chunkIndex = Math.floor(idx / chunkSize);
  26034. var chunkOffset = idx % chunkSize;
  26035. // Store the data by dimensions
  26036. for (var k = 0; k < dimLen; k++) {
  26037. var dim = dimensions[k];
  26038. var dimStorage = storage[dim][chunkIndex];
  26039. // PENDING NULL is empty or zero
  26040. var val = this._dimValueGetter(dataItem, dim, idx, k);
  26041. dimStorage[chunkOffset] = val;
  26042. var dimRawExtent = rawExtent[dim];
  26043. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26044. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26045. }
  26046. // ??? FIXME not check by pure but sourceFormat?
  26047. // TODO refactor these logic.
  26048. if (!rawData.pure) {
  26049. var name = nameList[idx];
  26050. if (dataItem && name == null) {
  26051. // If dataItem is {name: ...}, it has highest priority.
  26052. // That is appropriate for many common cases.
  26053. if (dataItem.name != null) {
  26054. // There is no other place to persistent dataItem.name,
  26055. // so save it to nameList.
  26056. nameList[idx] = name = dataItem.name;
  26057. }
  26058. else if (nameDimIdx != null) {
  26059. var nameDim = dimensions[nameDimIdx];
  26060. var nameDimChunk = storage[nameDim][chunkIndex];
  26061. if (nameDimChunk) {
  26062. name = nameDimChunk[chunkOffset];
  26063. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  26064. if (ordinalMeta && ordinalMeta.categories.length) {
  26065. name = ordinalMeta.categories[name];
  26066. }
  26067. }
  26068. }
  26069. }
  26070. // Try using the id in option
  26071. // id or name is used on dynamical data, mapping old and new items.
  26072. var id = dataItem == null ? null : dataItem.id;
  26073. if (id == null && name != null) {
  26074. // Use name as id and add counter to avoid same name
  26075. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  26076. id = name;
  26077. if (nameRepeatCount[name] > 0) {
  26078. id += '__ec__' + nameRepeatCount[name];
  26079. }
  26080. nameRepeatCount[name]++;
  26081. }
  26082. id != null && (idList[idx] = id);
  26083. }
  26084. }
  26085. if (!rawData.persistent && rawData.clean) {
  26086. // Clean unused data if data source is typed array.
  26087. rawData.clean();
  26088. }
  26089. this._rawCount = this._count = end;
  26090. // Reset data extent
  26091. this._extent = {};
  26092. prepareInvertedIndex(this);
  26093. };
  26094. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  26095. var DataCtor = dataCtors[dimInfo.type];
  26096. var lastChunkIndex = chunkCount - 1;
  26097. var dim = dimInfo.name;
  26098. var resizeChunkArray = storage[dim][lastChunkIndex];
  26099. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  26100. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  26101. // The cost of the copy is probably inconsiderable
  26102. // within the initial chunkSize.
  26103. for (var j = 0; j < resizeChunkArray.length; j++) {
  26104. newStore[j] = resizeChunkArray[j];
  26105. }
  26106. storage[dim][lastChunkIndex] = newStore;
  26107. }
  26108. // Create new chunks.
  26109. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  26110. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  26111. }
  26112. }
  26113. function prepareInvertedIndex(list) {
  26114. var invertedIndicesMap = list._invertedIndicesMap;
  26115. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  26116. var dimInfo = list._dimensionInfos[dim];
  26117. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  26118. var ordinalMeta = dimInfo.ordinalMeta;
  26119. if (ordinalMeta) {
  26120. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  26121. ordinalMeta.categories.length
  26122. );
  26123. // The default value of TypedArray is 0. To avoid miss
  26124. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  26125. for (var i = 0; i < invertedIndices.length; i++) {
  26126. invertedIndices[i] = INDEX_NOT_FOUND;
  26127. }
  26128. for (var i = 0; i < list._count; i++) {
  26129. // Only support the case that all values are distinct.
  26130. invertedIndices[list.get(dim, i)] = i;
  26131. }
  26132. }
  26133. });
  26134. }
  26135. function getRawValueFromStore(list, dimIndex, rawIndex) {
  26136. var val;
  26137. if (dimIndex != null) {
  26138. var chunkSize = list._chunkSize;
  26139. var chunkIndex = Math.floor(rawIndex / chunkSize);
  26140. var chunkOffset = rawIndex % chunkSize;
  26141. var dim = list.dimensions[dimIndex];
  26142. var chunk = list._storage[dim][chunkIndex];
  26143. if (chunk) {
  26144. val = chunk[chunkOffset];
  26145. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  26146. if (ordinalMeta && ordinalMeta.categories.length) {
  26147. val = ordinalMeta.categories[val];
  26148. }
  26149. }
  26150. }
  26151. return val;
  26152. }
  26153. /**
  26154. * @return {number}
  26155. */
  26156. listProto.count = function () {
  26157. return this._count;
  26158. };
  26159. listProto.getIndices = function () {
  26160. var newIndices;
  26161. var indices = this._indices;
  26162. if (indices) {
  26163. var Ctor = indices.constructor;
  26164. var thisCount = this._count;
  26165. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  26166. if (Ctor === Array) {
  26167. newIndices = new Ctor(thisCount);
  26168. for (var i = 0; i < thisCount; i++) {
  26169. newIndices[i] = indices[i];
  26170. }
  26171. }
  26172. else {
  26173. newIndices = new Ctor(indices.buffer, 0, thisCount);
  26174. }
  26175. }
  26176. else {
  26177. var Ctor = getIndicesCtor(this);
  26178. var newIndices = new Ctor(this.count());
  26179. for (var i = 0; i < newIndices.length; i++) {
  26180. newIndices[i] = i;
  26181. }
  26182. }
  26183. return newIndices;
  26184. };
  26185. /**
  26186. * Get value. Return NaN if idx is out of range.
  26187. * @param {string} dim Dim must be concrete name.
  26188. * @param {number} idx
  26189. * @param {boolean} stack
  26190. * @return {number}
  26191. */
  26192. listProto.get = function (dim, idx /*, stack */) {
  26193. if (!(idx >= 0 && idx < this._count)) {
  26194. return NaN;
  26195. }
  26196. var storage = this._storage;
  26197. if (!storage[dim]) {
  26198. // TODO Warn ?
  26199. return NaN;
  26200. }
  26201. idx = this.getRawIndex(idx);
  26202. var chunkIndex = Math.floor(idx / this._chunkSize);
  26203. var chunkOffset = idx % this._chunkSize;
  26204. var chunkStore = storage[dim][chunkIndex];
  26205. var value = chunkStore[chunkOffset];
  26206. // FIXME ordinal data type is not stackable
  26207. // if (stack) {
  26208. // var dimensionInfo = this._dimensionInfos[dim];
  26209. // if (dimensionInfo && dimensionInfo.stackable) {
  26210. // var stackedOn = this.stackedOn;
  26211. // while (stackedOn) {
  26212. // // Get no stacked data of stacked on
  26213. // var stackedValue = stackedOn.get(dim, idx);
  26214. // // Considering positive stack, negative stack and empty data
  26215. // if ((value >= 0 && stackedValue > 0) // Positive stack
  26216. // || (value <= 0 && stackedValue < 0) // Negative stack
  26217. // ) {
  26218. // value += stackedValue;
  26219. // }
  26220. // stackedOn = stackedOn.stackedOn;
  26221. // }
  26222. // }
  26223. // }
  26224. return value;
  26225. };
  26226. /**
  26227. * @param {string} dim concrete dim
  26228. * @param {number} rawIndex
  26229. * @return {number|string}
  26230. */
  26231. listProto.getByRawIndex = function (dim, rawIdx) {
  26232. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  26233. return NaN;
  26234. }
  26235. var dimStore = this._storage[dim];
  26236. if (!dimStore) {
  26237. // TODO Warn ?
  26238. return NaN;
  26239. }
  26240. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  26241. var chunkOffset = rawIdx % this._chunkSize;
  26242. var chunkStore = dimStore[chunkIndex];
  26243. return chunkStore[chunkOffset];
  26244. };
  26245. /**
  26246. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  26247. * Hack a much simpler _getFast
  26248. * @private
  26249. */
  26250. listProto._getFast = function (dim, rawIdx) {
  26251. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  26252. var chunkOffset = rawIdx % this._chunkSize;
  26253. var chunkStore = this._storage[dim][chunkIndex];
  26254. return chunkStore[chunkOffset];
  26255. };
  26256. /**
  26257. * Get value for multi dimensions.
  26258. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  26259. * @param {number} idx
  26260. * @return {number}
  26261. */
  26262. listProto.getValues = function (dimensions, idx /*, stack */) {
  26263. var values = [];
  26264. if (!isArray(dimensions)) {
  26265. // stack = idx;
  26266. idx = dimensions;
  26267. dimensions = this.dimensions;
  26268. }
  26269. for (var i = 0, len = dimensions.length; i < len; i++) {
  26270. values.push(this.get(dimensions[i], idx /*, stack */));
  26271. }
  26272. return values;
  26273. };
  26274. /**
  26275. * If value is NaN. Inlcuding '-'
  26276. * Only check the coord dimensions.
  26277. * @param {string} dim
  26278. * @param {number} idx
  26279. * @return {number}
  26280. */
  26281. listProto.hasValue = function (idx) {
  26282. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  26283. var dimensionInfos = this._dimensionInfos;
  26284. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  26285. if (
  26286. // Ordinal type can be string or number
  26287. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  26288. // FIXME check ordinal when using index?
  26289. && isNaN(this.get(dataDimsOnCoord[i], idx))
  26290. ) {
  26291. return false;
  26292. }
  26293. }
  26294. return true;
  26295. };
  26296. /**
  26297. * Get extent of data in one dimension
  26298. * @param {string} dim
  26299. * @param {boolean} stack
  26300. */
  26301. listProto.getDataExtent = function (dim /*, stack */) {
  26302. // Make sure use concrete dim as cache name.
  26303. dim = this.getDimension(dim);
  26304. var dimData = this._storage[dim];
  26305. var initialExtent = getInitialExtent();
  26306. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  26307. if (!dimData) {
  26308. return initialExtent;
  26309. }
  26310. // Make more strict checkings to ensure hitting cache.
  26311. var currEnd = this.count();
  26312. // var cacheName = [dim, !!stack].join('_');
  26313. // var cacheName = dim;
  26314. // Consider the most cases when using data zoom, `getDataExtent`
  26315. // happened before filtering. We cache raw extent, which is not
  26316. // necessary to be cleared and recalculated when restore data.
  26317. var useRaw = !this._indices; // && !stack;
  26318. var dimExtent;
  26319. if (useRaw) {
  26320. return this._rawExtent[dim].slice();
  26321. }
  26322. dimExtent = this._extent[dim];
  26323. if (dimExtent) {
  26324. return dimExtent.slice();
  26325. }
  26326. dimExtent = initialExtent;
  26327. var min = dimExtent[0];
  26328. var max = dimExtent[1];
  26329. for (var i = 0; i < currEnd; i++) {
  26330. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  26331. var value = this._getFast(dim, this.getRawIndex(i));
  26332. value < min && (min = value);
  26333. value > max && (max = value);
  26334. }
  26335. dimExtent = [min, max];
  26336. this._extent[dim] = dimExtent;
  26337. return dimExtent;
  26338. };
  26339. /**
  26340. * Optimize for the scenario that data is filtered by a given extent.
  26341. * Consider that if data amount is more than hundreds of thousand,
  26342. * extent calculation will cost more than 10ms and the cache will
  26343. * be erased because of the filtering.
  26344. */
  26345. listProto.getApproximateExtent = function (dim /*, stack */) {
  26346. dim = this.getDimension(dim);
  26347. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  26348. };
  26349. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  26350. dim = this.getDimension(dim);
  26351. this._approximateExtent[dim] = extent.slice();
  26352. };
  26353. /**
  26354. * @param {string} key
  26355. * @return {*}
  26356. */
  26357. listProto.getCalculationInfo = function (key) {
  26358. return this._calculationInfo[key];
  26359. };
  26360. /**
  26361. * @param {string|Object} key or k-v object
  26362. * @param {*} [value]
  26363. */
  26364. listProto.setCalculationInfo = function (key, value) {
  26365. isObject$4(key)
  26366. ? extend(this._calculationInfo, key)
  26367. : (this._calculationInfo[key] = value);
  26368. };
  26369. /**
  26370. * Get sum of data in one dimension
  26371. * @param {string} dim
  26372. */
  26373. listProto.getSum = function (dim /*, stack */) {
  26374. var dimData = this._storage[dim];
  26375. var sum = 0;
  26376. if (dimData) {
  26377. for (var i = 0, len = this.count(); i < len; i++) {
  26378. var value = this.get(dim, i /*, stack */);
  26379. if (!isNaN(value)) {
  26380. sum += value;
  26381. }
  26382. }
  26383. }
  26384. return sum;
  26385. };
  26386. /**
  26387. * Get median of data in one dimension
  26388. * @param {string} dim
  26389. */
  26390. listProto.getMedian = function (dim /*, stack */) {
  26391. var dimDataArray = [];
  26392. // map all data of one dimension
  26393. this.each(dim, function (val, idx) {
  26394. if (!isNaN(val)) {
  26395. dimDataArray.push(val);
  26396. }
  26397. });
  26398. // TODO
  26399. // Use quick select?
  26400. // immutability & sort
  26401. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  26402. return a - b;
  26403. });
  26404. var len = this.count();
  26405. // calculate median
  26406. return len === 0
  26407. ? 0
  26408. : len % 2 === 1
  26409. ? sortedDimDataArray[(len - 1) / 2]
  26410. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  26411. };
  26412. // /**
  26413. // * Retreive the index with given value
  26414. // * @param {string} dim Concrete dimension.
  26415. // * @param {number} value
  26416. // * @return {number}
  26417. // */
  26418. // Currently incorrect: should return dataIndex but not rawIndex.
  26419. // Do not fix it until this method is to be used somewhere.
  26420. // FIXME Precision of float value
  26421. // listProto.indexOf = function (dim, value) {
  26422. // var storage = this._storage;
  26423. // var dimData = storage[dim];
  26424. // var chunkSize = this._chunkSize;
  26425. // if (dimData) {
  26426. // for (var i = 0, len = this.count(); i < len; i++) {
  26427. // var chunkIndex = Math.floor(i / chunkSize);
  26428. // var chunkOffset = i % chunkSize;
  26429. // if (dimData[chunkIndex][chunkOffset] === value) {
  26430. // return i;
  26431. // }
  26432. // }
  26433. // }
  26434. // return -1;
  26435. // };
  26436. /**
  26437. * Only support the dimension which inverted index created.
  26438. * Do not support other cases until required.
  26439. * @param {string} concrete dim
  26440. * @param {number|string} value
  26441. * @return {number} rawIndex
  26442. */
  26443. listProto.rawIndexOf = function (dim, value) {
  26444. var invertedIndices = dim && this._invertedIndicesMap[dim];
  26445. if (__DEV__) {
  26446. if (!invertedIndices) {
  26447. throw new Error('Do not supported yet');
  26448. }
  26449. }
  26450. var rawIndex = invertedIndices[value];
  26451. if (rawIndex == null || isNaN(rawIndex)) {
  26452. return INDEX_NOT_FOUND;
  26453. }
  26454. return rawIndex;
  26455. };
  26456. /**
  26457. * Retreive the index with given name
  26458. * @param {number} idx
  26459. * @param {number} name
  26460. * @return {number}
  26461. */
  26462. listProto.indexOfName = function (name) {
  26463. for (var i = 0, len = this.count(); i < len; i++) {
  26464. if (this.getName(i) === name) {
  26465. return i;
  26466. }
  26467. }
  26468. return -1;
  26469. };
  26470. /**
  26471. * Retreive the index with given raw data index
  26472. * @param {number} idx
  26473. * @param {number} name
  26474. * @return {number}
  26475. */
  26476. listProto.indexOfRawIndex = function (rawIndex) {
  26477. if (!this._indices) {
  26478. return rawIndex;
  26479. }
  26480. if (rawIndex >= this._rawCount || rawIndex < 0) {
  26481. return -1;
  26482. }
  26483. // Indices are ascending
  26484. var indices = this._indices;
  26485. // If rawIndex === dataIndex
  26486. var rawDataIndex = indices[rawIndex];
  26487. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  26488. return rawIndex;
  26489. }
  26490. var left = 0;
  26491. var right = this._count - 1;
  26492. while (left <= right) {
  26493. var mid = (left + right) / 2 | 0;
  26494. if (indices[mid] < rawIndex) {
  26495. left = mid + 1;
  26496. }
  26497. else if (indices[mid] > rawIndex) {
  26498. right = mid - 1;
  26499. }
  26500. else {
  26501. return mid;
  26502. }
  26503. }
  26504. return -1;
  26505. };
  26506. /**
  26507. * Retreive the index of nearest value
  26508. * @param {string} dim
  26509. * @param {number} value
  26510. * @param {number} [maxDistance=Infinity]
  26511. * @return {Array.<number>} Considere multiple points has the same value.
  26512. */
  26513. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  26514. var storage = this._storage;
  26515. var dimData = storage[dim];
  26516. var nearestIndices = [];
  26517. if (!dimData) {
  26518. return nearestIndices;
  26519. }
  26520. if (maxDistance == null) {
  26521. maxDistance = Infinity;
  26522. }
  26523. var minDist = Number.MAX_VALUE;
  26524. var minDiff = -1;
  26525. for (var i = 0, len = this.count(); i < len; i++) {
  26526. var diff = value - this.get(dim, i /*, stack */);
  26527. var dist = Math.abs(diff);
  26528. if (diff <= maxDistance && dist <= minDist) {
  26529. // For the case of two data are same on xAxis, which has sequence data.
  26530. // Show the nearest index
  26531. // https://github.com/ecomfe/echarts/issues/2869
  26532. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  26533. minDist = dist;
  26534. minDiff = diff;
  26535. nearestIndices.length = 0;
  26536. }
  26537. nearestIndices.push(i);
  26538. }
  26539. }
  26540. return nearestIndices;
  26541. };
  26542. /**
  26543. * Get raw data index
  26544. * @param {number} idx
  26545. * @return {number}
  26546. */
  26547. listProto.getRawIndex = getRawIndexWithoutIndices;
  26548. function getRawIndexWithoutIndices(idx) {
  26549. return idx;
  26550. }
  26551. function getRawIndexWithIndices(idx) {
  26552. if (idx < this._count && idx >= 0) {
  26553. return this._indices[idx];
  26554. }
  26555. return -1;
  26556. }
  26557. /**
  26558. * Get raw data item
  26559. * @param {number} idx
  26560. * @return {number}
  26561. */
  26562. listProto.getRawDataItem = function (idx) {
  26563. if (!this._rawData.persistent) {
  26564. var val = [];
  26565. for (var i = 0; i < this.dimensions.length; i++) {
  26566. var dim = this.dimensions[i];
  26567. val.push(this.get(dim, idx));
  26568. }
  26569. return val;
  26570. }
  26571. else {
  26572. return this._rawData.getItem(this.getRawIndex(idx));
  26573. }
  26574. };
  26575. /**
  26576. * @param {number} idx
  26577. * @param {boolean} [notDefaultIdx=false]
  26578. * @return {string}
  26579. */
  26580. listProto.getName = function (idx) {
  26581. var rawIndex = this.getRawIndex(idx);
  26582. return this._nameList[rawIndex]
  26583. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  26584. || '';
  26585. };
  26586. /**
  26587. * @param {number} idx
  26588. * @param {boolean} [notDefaultIdx=false]
  26589. * @return {string}
  26590. */
  26591. listProto.getId = function (idx) {
  26592. return getId(this, this.getRawIndex(idx));
  26593. };
  26594. function getId(list, rawIndex) {
  26595. var id = list._idList[rawIndex];
  26596. if (id == null) {
  26597. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  26598. }
  26599. if (id == null) {
  26600. // FIXME Check the usage in graph, should not use prefix.
  26601. id = ID_PREFIX + rawIndex;
  26602. }
  26603. return id;
  26604. }
  26605. function normalizeDimensions(dimensions) {
  26606. if (!isArray(dimensions)) {
  26607. dimensions = [dimensions];
  26608. }
  26609. return dimensions;
  26610. }
  26611. function validateDimensions(list, dims) {
  26612. for (var i = 0; i < dims.length; i++) {
  26613. // stroage may be empty when no data, so use
  26614. // dimensionInfos to check.
  26615. if (!list._dimensionInfos[dims[i]]) {
  26616. console.error('Unkown dimension ' + dims[i]);
  26617. }
  26618. }
  26619. }
  26620. /**
  26621. * Data iteration
  26622. * @param {string|Array.<string>}
  26623. * @param {Function} cb
  26624. * @param {*} [context=this]
  26625. *
  26626. * @example
  26627. * list.each('x', function (x, idx) {});
  26628. * list.each(['x', 'y'], function (x, y, idx) {});
  26629. * list.each(function (idx) {})
  26630. */
  26631. listProto.each = function (dims, cb, context, contextCompat) {
  26632. 'use strict';
  26633. if (!this._count) {
  26634. return;
  26635. }
  26636. if (typeof dims === 'function') {
  26637. contextCompat = context;
  26638. context = cb;
  26639. cb = dims;
  26640. dims = [];
  26641. }
  26642. // contextCompat just for compat echarts3
  26643. context = context || contextCompat || this;
  26644. dims = map(normalizeDimensions(dims), this.getDimension, this);
  26645. if (__DEV__) {
  26646. validateDimensions(this, dims);
  26647. }
  26648. var dimSize = dims.length;
  26649. for (var i = 0; i < this.count(); i++) {
  26650. // Simple optimization
  26651. switch (dimSize) {
  26652. case 0:
  26653. cb.call(context, i);
  26654. break;
  26655. case 1:
  26656. cb.call(context, this.get(dims[0], i), i);
  26657. break;
  26658. case 2:
  26659. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  26660. break;
  26661. default:
  26662. var k = 0;
  26663. var value = [];
  26664. for (; k < dimSize; k++) {
  26665. value[k] = this.get(dims[k], i);
  26666. }
  26667. // Index
  26668. value[k] = i;
  26669. cb.apply(context, value);
  26670. }
  26671. }
  26672. };
  26673. /**
  26674. * Data filter
  26675. * @param {string|Array.<string>}
  26676. * @param {Function} cb
  26677. * @param {*} [context=this]
  26678. */
  26679. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  26680. 'use strict';
  26681. if (!this._count) {
  26682. return;
  26683. }
  26684. if (typeof dimensions === 'function') {
  26685. contextCompat = context;
  26686. context = cb;
  26687. cb = dimensions;
  26688. dimensions = [];
  26689. }
  26690. // contextCompat just for compat echarts3
  26691. context = context || contextCompat || this;
  26692. dimensions = map(
  26693. normalizeDimensions(dimensions), this.getDimension, this
  26694. );
  26695. if (__DEV__) {
  26696. validateDimensions(this, dimensions);
  26697. }
  26698. var count = this.count();
  26699. var Ctor = getIndicesCtor(this);
  26700. var newIndices = new Ctor(count);
  26701. var value = [];
  26702. var dimSize = dimensions.length;
  26703. var offset = 0;
  26704. var dim0 = dimensions[0];
  26705. for (var i = 0; i < count; i++) {
  26706. var keep;
  26707. var rawIdx = this.getRawIndex(i);
  26708. // Simple optimization
  26709. if (dimSize === 0) {
  26710. keep = cb.call(context, i);
  26711. }
  26712. else if (dimSize === 1) {
  26713. var val = this._getFast(dim0, rawIdx);
  26714. keep = cb.call(context, val, i);
  26715. }
  26716. else {
  26717. for (var k = 0; k < dimSize; k++) {
  26718. value[k] = this._getFast(dim0, rawIdx);
  26719. }
  26720. value[k] = i;
  26721. keep = cb.apply(context, value);
  26722. }
  26723. if (keep) {
  26724. newIndices[offset++] = rawIdx;
  26725. }
  26726. }
  26727. // Set indices after filtered.
  26728. if (offset < count) {
  26729. this._indices = newIndices;
  26730. }
  26731. this._count = offset;
  26732. // Reset data extent
  26733. this._extent = {};
  26734. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26735. return this;
  26736. };
  26737. /**
  26738. * Select data in range. (For optimization of filter)
  26739. * (Manually inline code, support 5 million data filtering in data zoom.)
  26740. */
  26741. listProto.selectRange = function (range) {
  26742. 'use strict';
  26743. if (!this._count) {
  26744. return;
  26745. }
  26746. var dimensions = [];
  26747. for (var dim in range) {
  26748. if (range.hasOwnProperty(dim)) {
  26749. dimensions.push(dim);
  26750. }
  26751. }
  26752. if (__DEV__) {
  26753. validateDimensions(this, dimensions);
  26754. }
  26755. var dimSize = dimensions.length;
  26756. if (!dimSize) {
  26757. return;
  26758. }
  26759. var originalCount = this.count();
  26760. var Ctor = getIndicesCtor(this);
  26761. var newIndices = new Ctor(originalCount);
  26762. var offset = 0;
  26763. var dim0 = dimensions[0];
  26764. var min = range[dim0][0];
  26765. var max = range[dim0][1];
  26766. var quickFinished = false;
  26767. if (!this._indices) {
  26768. // Extreme optimization for common case. About 2x faster in chrome.
  26769. var idx = 0;
  26770. if (dimSize === 1) {
  26771. var dimStorage = this._storage[dimensions[0]];
  26772. for (var k = 0; k < this._chunkCount; k++) {
  26773. var chunkStorage = dimStorage[k];
  26774. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  26775. for (var i = 0; i < len; i++) {
  26776. var val = chunkStorage[i];
  26777. // NaN will not be filtered. Consider the case, in line chart, empty
  26778. // value indicates the line should be broken. But for the case like
  26779. // scatter plot, a data item with empty value will not be rendered,
  26780. // but the axis extent may be effected if some other dim of the data
  26781. // item has value. Fortunately it is not a significant negative effect.
  26782. if (
  26783. (val >= min && val <= max) || isNaN(val)
  26784. ) {
  26785. newIndices[offset++] = idx;
  26786. }
  26787. idx++;
  26788. }
  26789. }
  26790. quickFinished = true;
  26791. }
  26792. else if (dimSize === 2) {
  26793. var dimStorage = this._storage[dim0];
  26794. var dimStorage2 = this._storage[dimensions[1]];
  26795. var min2 = range[dimensions[1]][0];
  26796. var max2 = range[dimensions[1]][1];
  26797. for (var k = 0; k < this._chunkCount; k++) {
  26798. var chunkStorage = dimStorage[k];
  26799. var chunkStorage2 = dimStorage2[k];
  26800. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  26801. for (var i = 0; i < len; i++) {
  26802. var val = chunkStorage[i];
  26803. var val2 = chunkStorage2[i];
  26804. // Do not filter NaN, see comment above.
  26805. if ((
  26806. (val >= min && val <= max) || isNaN(val)
  26807. )
  26808. && (
  26809. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  26810. )
  26811. ) {
  26812. newIndices[offset++] = idx;
  26813. }
  26814. idx++;
  26815. }
  26816. }
  26817. quickFinished = true;
  26818. }
  26819. }
  26820. if (!quickFinished) {
  26821. if (dimSize === 1) {
  26822. for (var i = 0; i < originalCount; i++) {
  26823. var rawIndex = this.getRawIndex(i);
  26824. var val = this._getFast(dim0, rawIndex);
  26825. // Do not filter NaN, see comment above.
  26826. if (
  26827. (val >= min && val <= max) || isNaN(val)
  26828. ) {
  26829. newIndices[offset++] = rawIndex;
  26830. }
  26831. }
  26832. }
  26833. else {
  26834. for (var i = 0; i < originalCount; i++) {
  26835. var keep = true;
  26836. var rawIndex = this.getRawIndex(i);
  26837. for (var k = 0; k < dimSize; k++) {
  26838. var dimk = dimensions[k];
  26839. var val = this._getFast(dim, rawIndex);
  26840. // Do not filter NaN, see comment above.
  26841. if (val < range[dimk][0] || val > range[dimk][1]) {
  26842. keep = false;
  26843. }
  26844. }
  26845. if (keep) {
  26846. newIndices[offset++] = this.getRawIndex(i);
  26847. }
  26848. }
  26849. }
  26850. }
  26851. // Set indices after filtered.
  26852. if (offset < originalCount) {
  26853. this._indices = newIndices;
  26854. }
  26855. this._count = offset;
  26856. // Reset data extent
  26857. this._extent = {};
  26858. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26859. return this;
  26860. };
  26861. /**
  26862. * Data mapping to a plain array
  26863. * @param {string|Array.<string>} [dimensions]
  26864. * @param {Function} cb
  26865. * @param {*} [context=this]
  26866. * @return {Array}
  26867. */
  26868. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  26869. 'use strict';
  26870. if (typeof dimensions === 'function') {
  26871. contextCompat = context;
  26872. context = cb;
  26873. cb = dimensions;
  26874. dimensions = [];
  26875. }
  26876. // contextCompat just for compat echarts3
  26877. context = context || contextCompat || this;
  26878. var result = [];
  26879. this.each(dimensions, function () {
  26880. result.push(cb && cb.apply(this, arguments));
  26881. }, context);
  26882. return result;
  26883. };
  26884. // Data in excludeDimensions is copied, otherwise transfered.
  26885. function cloneListForMapAndSample(original, excludeDimensions) {
  26886. var allDimensions = original.dimensions;
  26887. var list = new List(
  26888. map(allDimensions, original.getDimensionInfo, original),
  26889. original.hostModel
  26890. );
  26891. // FIXME If needs stackedOn, value may already been stacked
  26892. transferProperties(list, original);
  26893. var storage = list._storage = {};
  26894. var originalStorage = original._storage;
  26895. // Init storage
  26896. for (var i = 0; i < allDimensions.length; i++) {
  26897. var dim = allDimensions[i];
  26898. if (originalStorage[dim]) {
  26899. // Notice that we do not reset invertedIndicesMap here, becuase
  26900. // there is no scenario of mapping or sampling ordinal dimension.
  26901. if (indexOf(excludeDimensions, dim) >= 0) {
  26902. storage[dim] = cloneDimStore(originalStorage[dim]);
  26903. list._rawExtent[dim] = getInitialExtent();
  26904. list._extent[dim] = null;
  26905. }
  26906. else {
  26907. // Direct reference for other dimensions
  26908. storage[dim] = originalStorage[dim];
  26909. }
  26910. }
  26911. }
  26912. return list;
  26913. }
  26914. function cloneDimStore(originalDimStore) {
  26915. var newDimStore = new Array(originalDimStore.length);
  26916. for (var j = 0; j < originalDimStore.length; j++) {
  26917. newDimStore[j] = cloneChunk(originalDimStore[j]);
  26918. }
  26919. return newDimStore;
  26920. }
  26921. function getInitialExtent() {
  26922. return [Infinity, -Infinity];
  26923. }
  26924. /**
  26925. * Data mapping to a new List with given dimensions
  26926. * @param {string|Array.<string>} dimensions
  26927. * @param {Function} cb
  26928. * @param {*} [context=this]
  26929. * @return {Array}
  26930. */
  26931. listProto.map = function (dimensions, cb, context, contextCompat) {
  26932. 'use strict';
  26933. // contextCompat just for compat echarts3
  26934. context = context || contextCompat || this;
  26935. dimensions = map(
  26936. normalizeDimensions(dimensions), this.getDimension, this
  26937. );
  26938. if (__DEV__) {
  26939. validateDimensions(this, dimensions);
  26940. }
  26941. var list = cloneListForMapAndSample(this, dimensions);
  26942. // Following properties are all immutable.
  26943. // So we can reference to the same value
  26944. list._indices = this._indices;
  26945. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26946. var storage = list._storage;
  26947. var tmpRetValue = [];
  26948. var chunkSize = this._chunkSize;
  26949. var dimSize = dimensions.length;
  26950. var dataCount = this.count();
  26951. var values = [];
  26952. var rawExtent = list._rawExtent;
  26953. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  26954. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  26955. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  26956. }
  26957. values[dimSize] = dataIndex;
  26958. var retValue = cb && cb.apply(context, values);
  26959. if (retValue != null) {
  26960. // a number or string (in oridinal dimension)?
  26961. if (typeof retValue !== 'object') {
  26962. tmpRetValue[0] = retValue;
  26963. retValue = tmpRetValue;
  26964. }
  26965. var rawIndex = this.getRawIndex(dataIndex);
  26966. var chunkIndex = Math.floor(rawIndex / chunkSize);
  26967. var chunkOffset = rawIndex % chunkSize;
  26968. for (var i = 0; i < retValue.length; i++) {
  26969. var dim = dimensions[i];
  26970. var val = retValue[i];
  26971. var rawExtentOnDim = rawExtent[dim];
  26972. var dimStore = storage[dim];
  26973. if (dimStore) {
  26974. dimStore[chunkIndex][chunkOffset] = val;
  26975. }
  26976. if (val < rawExtentOnDim[0]) {
  26977. rawExtentOnDim[0] = val;
  26978. }
  26979. if (val > rawExtentOnDim[1]) {
  26980. rawExtentOnDim[1] = val;
  26981. }
  26982. }
  26983. }
  26984. }
  26985. return list;
  26986. };
  26987. /**
  26988. * Large data down sampling on given dimension
  26989. * @param {string} dimension
  26990. * @param {number} rate
  26991. * @param {Function} sampleValue
  26992. * @param {Function} sampleIndex Sample index for name and id
  26993. */
  26994. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  26995. var list = cloneListForMapAndSample(this, [dimension]);
  26996. var targetStorage = list._storage;
  26997. var frameValues = [];
  26998. var frameSize = Math.floor(1 / rate);
  26999. var dimStore = targetStorage[dimension];
  27000. var len = this.count();
  27001. var chunkSize = this._chunkSize;
  27002. var rawExtentOnDim = list._rawExtent[dimension];
  27003. var newIndices = new (getIndicesCtor(this))(len);
  27004. var offset = 0;
  27005. for (var i = 0; i < len; i += frameSize) {
  27006. // Last frame
  27007. if (frameSize > len - i) {
  27008. frameSize = len - i;
  27009. frameValues.length = frameSize;
  27010. }
  27011. for (var k = 0; k < frameSize; k++) {
  27012. var dataIdx = this.getRawIndex(i + k);
  27013. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  27014. var originalChunkOffset = dataIdx % chunkSize;
  27015. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  27016. }
  27017. var value = sampleValue(frameValues);
  27018. var sampleFrameIdx = this.getRawIndex(
  27019. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  27020. );
  27021. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  27022. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  27023. // Only write value on the filtered data
  27024. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  27025. if (value < rawExtentOnDim[0]) {
  27026. rawExtentOnDim[0] = value;
  27027. }
  27028. if (value > rawExtentOnDim[1]) {
  27029. rawExtentOnDim[1] = value;
  27030. }
  27031. newIndices[offset++] = sampleFrameIdx;
  27032. }
  27033. list._count = offset;
  27034. list._indices = newIndices;
  27035. list.getRawIndex = getRawIndexWithIndices;
  27036. return list;
  27037. };
  27038. /**
  27039. * Get model of one data item.
  27040. *
  27041. * @param {number} idx
  27042. */
  27043. // FIXME Model proxy ?
  27044. listProto.getItemModel = function (idx) {
  27045. var hostModel = this.hostModel;
  27046. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  27047. };
  27048. /**
  27049. * Create a data differ
  27050. * @param {module:echarts/data/List} otherList
  27051. * @return {module:echarts/data/DataDiffer}
  27052. */
  27053. listProto.diff = function (otherList) {
  27054. var thisList = this;
  27055. return new DataDiffer(
  27056. otherList ? otherList.getIndices() : [],
  27057. this.getIndices(),
  27058. function (idx) {
  27059. return getId(otherList, idx);
  27060. },
  27061. function (idx) {
  27062. return getId(thisList, idx);
  27063. }
  27064. );
  27065. };
  27066. /**
  27067. * Get visual property.
  27068. * @param {string} key
  27069. */
  27070. listProto.getVisual = function (key) {
  27071. var visual = this._visual;
  27072. return visual && visual[key];
  27073. };
  27074. /**
  27075. * Set visual property
  27076. * @param {string|Object} key
  27077. * @param {*} [value]
  27078. *
  27079. * @example
  27080. * setVisual('color', color);
  27081. * setVisual({
  27082. * 'color': color
  27083. * });
  27084. */
  27085. listProto.setVisual = function (key, val) {
  27086. if (isObject$4(key)) {
  27087. for (var name in key) {
  27088. if (key.hasOwnProperty(name)) {
  27089. this.setVisual(name, key[name]);
  27090. }
  27091. }
  27092. return;
  27093. }
  27094. this._visual = this._visual || {};
  27095. this._visual[key] = val;
  27096. };
  27097. /**
  27098. * Set layout property.
  27099. * @param {string|Object} key
  27100. * @param {*} [val]
  27101. */
  27102. listProto.setLayout = function (key, val) {
  27103. if (isObject$4(key)) {
  27104. for (var name in key) {
  27105. if (key.hasOwnProperty(name)) {
  27106. this.setLayout(name, key[name]);
  27107. }
  27108. }
  27109. return;
  27110. }
  27111. this._layout[key] = val;
  27112. };
  27113. /**
  27114. * Get layout property.
  27115. * @param {string} key.
  27116. * @return {*}
  27117. */
  27118. listProto.getLayout = function (key) {
  27119. return this._layout[key];
  27120. };
  27121. /**
  27122. * Get layout of single data item
  27123. * @param {number} idx
  27124. */
  27125. listProto.getItemLayout = function (idx) {
  27126. return this._itemLayouts[idx];
  27127. };
  27128. /**
  27129. * Set layout of single data item
  27130. * @param {number} idx
  27131. * @param {Object} layout
  27132. * @param {boolean=} [merge=false]
  27133. */
  27134. listProto.setItemLayout = function (idx, layout, merge$$1) {
  27135. this._itemLayouts[idx] = merge$$1
  27136. ? extend(this._itemLayouts[idx] || {}, layout)
  27137. : layout;
  27138. };
  27139. /**
  27140. * Clear all layout of single data item
  27141. */
  27142. listProto.clearItemLayouts = function () {
  27143. this._itemLayouts.length = 0;
  27144. };
  27145. /**
  27146. * Get visual property of single data item
  27147. * @param {number} idx
  27148. * @param {string} key
  27149. * @param {boolean} [ignoreParent=false]
  27150. */
  27151. listProto.getItemVisual = function (idx, key, ignoreParent) {
  27152. var itemVisual = this._itemVisuals[idx];
  27153. var val = itemVisual && itemVisual[key];
  27154. if (val == null && !ignoreParent) {
  27155. // Use global visual property
  27156. return this.getVisual(key);
  27157. }
  27158. return val;
  27159. };
  27160. /**
  27161. * Set visual property of single data item
  27162. *
  27163. * @param {number} idx
  27164. * @param {string|Object} key
  27165. * @param {*} [value]
  27166. *
  27167. * @example
  27168. * setItemVisual(0, 'color', color);
  27169. * setItemVisual(0, {
  27170. * 'color': color
  27171. * });
  27172. */
  27173. listProto.setItemVisual = function (idx, key, value) {
  27174. var itemVisual = this._itemVisuals[idx] || {};
  27175. var hasItemVisual = this.hasItemVisual;
  27176. this._itemVisuals[idx] = itemVisual;
  27177. if (isObject$4(key)) {
  27178. for (var name in key) {
  27179. if (key.hasOwnProperty(name)) {
  27180. itemVisual[name] = key[name];
  27181. hasItemVisual[name] = true;
  27182. }
  27183. }
  27184. return;
  27185. }
  27186. itemVisual[key] = value;
  27187. hasItemVisual[key] = true;
  27188. };
  27189. /**
  27190. * Clear itemVisuals and list visual.
  27191. */
  27192. listProto.clearAllVisual = function () {
  27193. this._visual = {};
  27194. this._itemVisuals = [];
  27195. this.hasItemVisual = {};
  27196. };
  27197. var setItemDataAndSeriesIndex = function (child) {
  27198. child.seriesIndex = this.seriesIndex;
  27199. child.dataIndex = this.dataIndex;
  27200. child.dataType = this.dataType;
  27201. };
  27202. /**
  27203. * Set graphic element relative to data. It can be set as null
  27204. * @param {number} idx
  27205. * @param {module:zrender/Element} [el]
  27206. */
  27207. listProto.setItemGraphicEl = function (idx, el) {
  27208. var hostModel = this.hostModel;
  27209. if (el) {
  27210. // Add data index and series index for indexing the data by element
  27211. // Useful in tooltip
  27212. el.dataIndex = idx;
  27213. el.dataType = this.dataType;
  27214. el.seriesIndex = hostModel && hostModel.seriesIndex;
  27215. if (el.type === 'group') {
  27216. el.traverse(setItemDataAndSeriesIndex, el);
  27217. }
  27218. }
  27219. this._graphicEls[idx] = el;
  27220. };
  27221. /**
  27222. * @param {number} idx
  27223. * @return {module:zrender/Element}
  27224. */
  27225. listProto.getItemGraphicEl = function (idx) {
  27226. return this._graphicEls[idx];
  27227. };
  27228. /**
  27229. * @param {Function} cb
  27230. * @param {*} context
  27231. */
  27232. listProto.eachItemGraphicEl = function (cb, context) {
  27233. each$1(this._graphicEls, function (el, idx) {
  27234. if (el) {
  27235. cb && cb.call(context, el, idx);
  27236. }
  27237. });
  27238. };
  27239. /**
  27240. * Shallow clone a new list except visual and layout properties, and graph elements.
  27241. * New list only change the indices.
  27242. */
  27243. listProto.cloneShallow = function (list) {
  27244. if (!list) {
  27245. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  27246. list = new List(dimensionInfoList, this.hostModel);
  27247. }
  27248. // FIXME
  27249. list._storage = this._storage;
  27250. transferProperties(list, this);
  27251. // Clone will not change the data extent and indices
  27252. if (this._indices) {
  27253. var Ctor = this._indices.constructor;
  27254. list._indices = new Ctor(this._indices);
  27255. }
  27256. else {
  27257. list._indices = null;
  27258. }
  27259. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27260. return list;
  27261. };
  27262. /**
  27263. * Wrap some method to add more feature
  27264. * @param {string} methodName
  27265. * @param {Function} injectFunction
  27266. */
  27267. listProto.wrapMethod = function (methodName, injectFunction) {
  27268. var originalMethod = this[methodName];
  27269. if (typeof originalMethod !== 'function') {
  27270. return;
  27271. }
  27272. this.__wrappedMethods = this.__wrappedMethods || [];
  27273. this.__wrappedMethods.push(methodName);
  27274. this[methodName] = function () {
  27275. var res = originalMethod.apply(this, arguments);
  27276. return injectFunction.apply(this, [res].concat(slice(arguments)));
  27277. };
  27278. };
  27279. // Methods that create a new list based on this list should be listed here.
  27280. // Notice that those method should `RETURN` the new list.
  27281. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  27282. // Methods that change indices of this list should be listed here.
  27283. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  27284. /*
  27285. * Licensed to the Apache Software Foundation (ASF) under one
  27286. * or more contributor license agreements. See the NOTICE file
  27287. * distributed with this work for additional information
  27288. * regarding copyright ownership. The ASF licenses this file
  27289. * to you under the Apache License, Version 2.0 (the
  27290. * "License"); you may not use this file except in compliance
  27291. * with the License. You may obtain a copy of the License at
  27292. *
  27293. * http://www.apache.org/licenses/LICENSE-2.0
  27294. *
  27295. * Unless required by applicable law or agreed to in writing,
  27296. * software distributed under the License is distributed on an
  27297. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27298. * KIND, either express or implied. See the License for the
  27299. * specific language governing permissions and limitations
  27300. * under the License.
  27301. */
  27302. /**
  27303. * @deprecated
  27304. * Use `echarts/data/helper/createDimensions` instead.
  27305. */
  27306. /**
  27307. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  27308. *
  27309. * Complete the dimensions array, by user defined `dimension` and `encode`,
  27310. * and guessing from the data structure.
  27311. * If no 'value' dimension specified, the first no-named dimension will be
  27312. * named as 'value'.
  27313. *
  27314. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  27315. * provides not only dim template, but also default order.
  27316. * properties: 'name', 'type', 'displayName'.
  27317. * `name` of each item provides default coord name.
  27318. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  27319. * provide dims count that the sysDim required.
  27320. * [{ordinalMeta}] can be specified.
  27321. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  27322. * @param {Object} [opt]
  27323. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  27324. * For example: ['asdf', {name, type}, ...].
  27325. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  27326. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  27327. * If not specified, extra dim names will be:
  27328. * 'value', 'value0', 'value1', ...
  27329. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  27330. * If `generateCoordCount` specified, the generated dim names will be:
  27331. * `generateCoord` + 0, `generateCoord` + 1, ...
  27332. * can be Infinity, indicate that use all of the remain columns.
  27333. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  27334. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  27335. * @return {Array.<Object>} [{
  27336. * name: string mandatory,
  27337. * displayName: string, the origin name in dimsDef, see source helper.
  27338. * If displayName given, the tooltip will displayed vertically.
  27339. * coordDim: string mandatory,
  27340. * coordDimIndex: number mandatory,
  27341. * type: string optional,
  27342. * otherDims: { never null/undefined
  27343. * tooltip: number optional,
  27344. * label: number optional,
  27345. * itemName: number optional,
  27346. * seriesName: number optional,
  27347. * },
  27348. * isExtraCoord: boolean true if coord is generated
  27349. * (not specified in encode and not series specified)
  27350. * other props ...
  27351. * }]
  27352. */
  27353. function completeDimensions(sysDims, source, opt) {
  27354. if (!Source.isInstance(source)) {
  27355. source = Source.seriesDataToSource(source);
  27356. }
  27357. opt = opt || {};
  27358. sysDims = (sysDims || []).slice();
  27359. var dimsDef = (opt.dimsDef || []).slice();
  27360. var encodeDef = createHashMap(opt.encodeDef);
  27361. var dataDimNameMap = createHashMap();
  27362. var coordDimNameMap = createHashMap();
  27363. // var valueCandidate;
  27364. var result = [];
  27365. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  27366. // Apply user defined dims (`name` and `type`) and init result.
  27367. for (var i = 0; i < dimCount; i++) {
  27368. var dimDefItem = dimsDef[i] = extend(
  27369. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  27370. );
  27371. var userDimName = dimDefItem.name;
  27372. var resultItem = result[i] = {otherDims: {}};
  27373. // Name will be applied later for avoiding duplication.
  27374. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  27375. // Only if `series.dimensions` is defined in option
  27376. // displayName, will be set, and dimension will be diplayed vertically in
  27377. // tooltip by default.
  27378. resultItem.name = resultItem.displayName = userDimName;
  27379. dataDimNameMap.set(userDimName, i);
  27380. }
  27381. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  27382. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  27383. }
  27384. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  27385. encodeDef.each(function (dataDims, coordDim) {
  27386. dataDims = normalizeToArray(dataDims).slice();
  27387. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  27388. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  27389. // this case.
  27390. if (dataDims.length === 1 && dataDims[0] < 0) {
  27391. encodeDef.set(coordDim, false);
  27392. return;
  27393. }
  27394. var validDataDims = encodeDef.set(coordDim, []);
  27395. each$1(dataDims, function (resultDimIdx, idx) {
  27396. // The input resultDimIdx can be dim name or index.
  27397. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  27398. if (resultDimIdx != null && resultDimIdx < dimCount) {
  27399. validDataDims[idx] = resultDimIdx;
  27400. applyDim(result[resultDimIdx], coordDim, idx);
  27401. }
  27402. });
  27403. });
  27404. // Apply templetes and default order from `sysDims`.
  27405. var availDimIdx = 0;
  27406. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  27407. var coordDim;
  27408. var sysDimItem;
  27409. var sysDimItemDimsDef;
  27410. var sysDimItemOtherDims;
  27411. if (isString(sysDimItem)) {
  27412. coordDim = sysDimItem;
  27413. sysDimItem = {};
  27414. }
  27415. else {
  27416. coordDim = sysDimItem.name;
  27417. var ordinalMeta = sysDimItem.ordinalMeta;
  27418. sysDimItem.ordinalMeta = null;
  27419. sysDimItem = clone(sysDimItem);
  27420. sysDimItem.ordinalMeta = ordinalMeta;
  27421. // `coordDimIndex` should not be set directly.
  27422. sysDimItemDimsDef = sysDimItem.dimsDef;
  27423. sysDimItemOtherDims = sysDimItem.otherDims;
  27424. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  27425. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  27426. }
  27427. var dataDims = encodeDef.get(coordDim);
  27428. // negative resultDimIdx means no need to mapping.
  27429. if (dataDims === false) {
  27430. return;
  27431. }
  27432. var dataDims = normalizeToArray(dataDims);
  27433. // dimensions provides default dim sequences.
  27434. if (!dataDims.length) {
  27435. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  27436. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  27437. availDimIdx++;
  27438. }
  27439. availDimIdx < result.length && dataDims.push(availDimIdx++);
  27440. }
  27441. }
  27442. // Apply templates.
  27443. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  27444. var resultItem = result[resultDimIdx];
  27445. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  27446. if (resultItem.name == null && sysDimItemDimsDef) {
  27447. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  27448. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  27449. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  27450. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  27451. }
  27452. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  27453. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  27454. });
  27455. });
  27456. function applyDim(resultItem, coordDim, coordDimIndex) {
  27457. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  27458. resultItem.otherDims[coordDim] = coordDimIndex;
  27459. }
  27460. else {
  27461. resultItem.coordDim = coordDim;
  27462. resultItem.coordDimIndex = coordDimIndex;
  27463. coordDimNameMap.set(coordDim, true);
  27464. }
  27465. }
  27466. // Make sure the first extra dim is 'value'.
  27467. var generateCoord = opt.generateCoord;
  27468. var generateCoordCount = opt.generateCoordCount;
  27469. var fromZero = generateCoordCount != null;
  27470. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  27471. var extra = generateCoord || 'value';
  27472. // Set dim `name` and other `coordDim` and other props.
  27473. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  27474. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  27475. var coordDim = resultItem.coordDim;
  27476. if (coordDim == null) {
  27477. resultItem.coordDim = genName(
  27478. extra, coordDimNameMap, fromZero
  27479. );
  27480. resultItem.coordDimIndex = 0;
  27481. if (!generateCoord || generateCoordCount <= 0) {
  27482. resultItem.isExtraCoord = true;
  27483. }
  27484. generateCoordCount--;
  27485. }
  27486. resultItem.name == null && (resultItem.name = genName(
  27487. resultItem.coordDim,
  27488. dataDimNameMap
  27489. ));
  27490. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  27491. resultItem.type = 'ordinal';
  27492. }
  27493. }
  27494. return result;
  27495. }
  27496. // ??? TODO
  27497. // Originally detect dimCount by data[0]. Should we
  27498. // optimize it to only by sysDims and dimensions and encode.
  27499. // So only necessary dims will be initialized.
  27500. // But
  27501. // (1) custom series should be considered. where other dims
  27502. // may be visited.
  27503. // (2) sometimes user need to calcualte bubble size or use visualMap
  27504. // on other dimensions besides coordSys needed.
  27505. // So, dims that is not used by system, should be shared in storage?
  27506. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  27507. // Note that the result dimCount should not small than columns count
  27508. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  27509. var dimCount = Math.max(
  27510. source.dimensionsDetectCount || 1,
  27511. sysDims.length,
  27512. dimsDef.length,
  27513. optDimCount || 0
  27514. );
  27515. each$1(sysDims, function (sysDimItem) {
  27516. var sysDimItemDimsDef = sysDimItem.dimsDef;
  27517. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  27518. });
  27519. return dimCount;
  27520. }
  27521. function genName(name, map$$1, fromZero) {
  27522. if (fromZero || map$$1.get(name) != null) {
  27523. var i = 0;
  27524. while (map$$1.get(name + i) != null) {
  27525. i++;
  27526. }
  27527. name += i;
  27528. }
  27529. map$$1.set(name, true);
  27530. return name;
  27531. }
  27532. /*
  27533. * Licensed to the Apache Software Foundation (ASF) under one
  27534. * or more contributor license agreements. See the NOTICE file
  27535. * distributed with this work for additional information
  27536. * regarding copyright ownership. The ASF licenses this file
  27537. * to you under the Apache License, Version 2.0 (the
  27538. * "License"); you may not use this file except in compliance
  27539. * with the License. You may obtain a copy of the License at
  27540. *
  27541. * http://www.apache.org/licenses/LICENSE-2.0
  27542. *
  27543. * Unless required by applicable law or agreed to in writing,
  27544. * software distributed under the License is distributed on an
  27545. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27546. * KIND, either express or implied. See the License for the
  27547. * specific language governing permissions and limitations
  27548. * under the License.
  27549. */
  27550. /**
  27551. * Substitute `completeDimensions`.
  27552. * `completeDimensions` is to be deprecated.
  27553. */
  27554. /**
  27555. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  27556. * @param {Object|Array} [opt]
  27557. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  27558. * @param {number} [opt.dimensionsCount]
  27559. * @param {string} [opt.generateCoord]
  27560. * @param {string} [opt.generateCoordCount]
  27561. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  27562. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  27563. * @return {Array.<Object>} dimensionsInfo
  27564. */
  27565. var createDimensions = function (source, opt) {
  27566. opt = opt || {};
  27567. return completeDimensions(opt.coordDimensions || [], source, {
  27568. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  27569. encodeDef: opt.encodeDefine || source.encodeDefine,
  27570. dimCount: opt.dimensionsCount,
  27571. generateCoord: opt.generateCoord,
  27572. generateCoordCount: opt.generateCoordCount
  27573. });
  27574. };
  27575. /*
  27576. * Licensed to the Apache Software Foundation (ASF) under one
  27577. * or more contributor license agreements. See the NOTICE file
  27578. * distributed with this work for additional information
  27579. * regarding copyright ownership. The ASF licenses this file
  27580. * to you under the Apache License, Version 2.0 (the
  27581. * "License"); you may not use this file except in compliance
  27582. * with the License. You may obtain a copy of the License at
  27583. *
  27584. * http://www.apache.org/licenses/LICENSE-2.0
  27585. *
  27586. * Unless required by applicable law or agreed to in writing,
  27587. * software distributed under the License is distributed on an
  27588. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27589. * KIND, either express or implied. See the License for the
  27590. * specific language governing permissions and limitations
  27591. * under the License.
  27592. */
  27593. /**
  27594. * Note that it is too complicated to support 3d stack by value
  27595. * (have to create two-dimension inverted index), so in 3d case
  27596. * we just support that stacked by index.
  27597. *
  27598. * @param {module:echarts/model/Series} seriesModel
  27599. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  27600. * The input dimensionInfoList will be modified.
  27601. * @param {Object} [opt]
  27602. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  27603. * @param {boolean} [opt.byIndex=false]
  27604. * @return {Object} calculationInfo
  27605. * {
  27606. * stackedDimension: string
  27607. * stackedByDimension: string
  27608. * isStackedByIndex: boolean
  27609. * stackedOverDimension: string
  27610. * stackResultDimension: string
  27611. * }
  27612. */
  27613. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  27614. opt = opt || {};
  27615. var byIndex = opt.byIndex;
  27616. var stackedCoordDimension = opt.stackedCoordDimension;
  27617. // Compatibal: when `stack` is set as '', do not stack.
  27618. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  27619. var stackedByDimInfo;
  27620. var stackedDimInfo;
  27621. var stackResultDimension;
  27622. var stackedOverDimension;
  27623. each$1(dimensionInfoList, function (dimensionInfo, index) {
  27624. if (isString(dimensionInfo)) {
  27625. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  27626. }
  27627. if (mayStack && !dimensionInfo.isExtraCoord) {
  27628. // Find the first ordinal dimension as the stackedByDimInfo.
  27629. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  27630. stackedByDimInfo = dimensionInfo;
  27631. }
  27632. // Find the first stackable dimension as the stackedDimInfo.
  27633. if (!stackedDimInfo
  27634. && dimensionInfo.type !== 'ordinal'
  27635. && dimensionInfo.type !== 'time'
  27636. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  27637. ) {
  27638. stackedDimInfo = dimensionInfo;
  27639. }
  27640. }
  27641. });
  27642. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  27643. // Compatible with previous design, value axis (time axis) only stack by index.
  27644. // It may make sense if the user provides elaborately constructed data.
  27645. byIndex = true;
  27646. }
  27647. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  27648. // That put stack logic in List is for using conveniently in echarts extensions, but it
  27649. // might not be a good way.
  27650. if (stackedDimInfo) {
  27651. // Use a weird name that not duplicated with other names.
  27652. stackResultDimension = '__\0ecstackresult';
  27653. stackedOverDimension = '__\0ecstackedover';
  27654. // Create inverted index to fast query index by value.
  27655. if (stackedByDimInfo) {
  27656. stackedByDimInfo.createInvertedIndices = true;
  27657. }
  27658. var stackedDimCoordDim = stackedDimInfo.coordDim;
  27659. var stackedDimType = stackedDimInfo.type;
  27660. var stackedDimCoordIndex = 0;
  27661. each$1(dimensionInfoList, function (dimensionInfo) {
  27662. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  27663. stackedDimCoordIndex++;
  27664. }
  27665. });
  27666. dimensionInfoList.push({
  27667. name: stackResultDimension,
  27668. coordDim: stackedDimCoordDim,
  27669. coordDimIndex: stackedDimCoordIndex,
  27670. type: stackedDimType,
  27671. isExtraCoord: true,
  27672. isCalculationCoord: true
  27673. });
  27674. stackedDimCoordIndex++;
  27675. dimensionInfoList.push({
  27676. name: stackedOverDimension,
  27677. // This dimension contains stack base (generally, 0), so do not set it as
  27678. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  27679. coordDim: stackedOverDimension,
  27680. coordDimIndex: stackedDimCoordIndex,
  27681. type: stackedDimType,
  27682. isExtraCoord: true,
  27683. isCalculationCoord: true
  27684. });
  27685. }
  27686. return {
  27687. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  27688. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  27689. isStackedByIndex: byIndex,
  27690. stackedOverDimension: stackedOverDimension,
  27691. stackResultDimension: stackResultDimension
  27692. };
  27693. }
  27694. /**
  27695. * @param {module:echarts/data/List} data
  27696. * @param {string} stackedDim
  27697. */
  27698. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  27699. // Each single series only maps to one pair of axis. So we do not need to
  27700. // check stackByDim, whatever stacked by a dimension or stacked by index.
  27701. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  27702. // && (
  27703. // stackedByDim != null
  27704. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  27705. // : data.getCalculationInfo('isStackedByIndex')
  27706. // );
  27707. }
  27708. /**
  27709. * @param {module:echarts/data/List} data
  27710. * @param {string} targetDim
  27711. * @param {string} [stackedByDim] If not input this parameter, check whether
  27712. * stacked by index.
  27713. * @return {string} dimension
  27714. */
  27715. function getStackedDimension(data, targetDim) {
  27716. return isDimensionStacked(data, targetDim)
  27717. ? data.getCalculationInfo('stackResultDimension')
  27718. : targetDim;
  27719. }
  27720. /*
  27721. * Licensed to the Apache Software Foundation (ASF) under one
  27722. * or more contributor license agreements. See the NOTICE file
  27723. * distributed with this work for additional information
  27724. * regarding copyright ownership. The ASF licenses this file
  27725. * to you under the Apache License, Version 2.0 (the
  27726. * "License"); you may not use this file except in compliance
  27727. * with the License. You may obtain a copy of the License at
  27728. *
  27729. * http://www.apache.org/licenses/LICENSE-2.0
  27730. *
  27731. * Unless required by applicable law or agreed to in writing,
  27732. * software distributed under the License is distributed on an
  27733. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27734. * KIND, either express or implied. See the License for the
  27735. * specific language governing permissions and limitations
  27736. * under the License.
  27737. */
  27738. /**
  27739. * @param {module:echarts/data/Source|Array} source Or raw data.
  27740. * @param {module:echarts/model/Series} seriesModel
  27741. * @param {Object} [opt]
  27742. * @param {string} [opt.generateCoord]
  27743. */
  27744. function createListFromArray(source, seriesModel, opt) {
  27745. opt = opt || {};
  27746. if (!Source.isInstance(source)) {
  27747. source = Source.seriesDataToSource(source);
  27748. }
  27749. var coordSysName = seriesModel.get('coordinateSystem');
  27750. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  27751. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  27752. var coordSysDimDefs;
  27753. if (coordSysDefine) {
  27754. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  27755. var dimInfo = {name: dim};
  27756. var axisModel = coordSysDefine.axisMap.get(dim);
  27757. if (axisModel) {
  27758. var axisType = axisModel.get('type');
  27759. dimInfo.type = getDimensionTypeByAxis(axisType);
  27760. // dimInfo.stackable = isStackable(axisType);
  27761. }
  27762. return dimInfo;
  27763. });
  27764. }
  27765. if (!coordSysDimDefs) {
  27766. // Get dimensions from registered coordinate system
  27767. coordSysDimDefs = (registeredCoordSys && (
  27768. registeredCoordSys.getDimensionsInfo
  27769. ? registeredCoordSys.getDimensionsInfo()
  27770. : registeredCoordSys.dimensions.slice()
  27771. )) || ['x', 'y'];
  27772. }
  27773. var dimInfoList = createDimensions(source, {
  27774. coordDimensions: coordSysDimDefs,
  27775. generateCoord: opt.generateCoord
  27776. });
  27777. var firstCategoryDimIndex;
  27778. var hasNameEncode;
  27779. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  27780. var coordDim = dimInfo.coordDim;
  27781. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  27782. if (categoryAxisModel) {
  27783. if (firstCategoryDimIndex == null) {
  27784. firstCategoryDimIndex = dimIndex;
  27785. }
  27786. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  27787. }
  27788. if (dimInfo.otherDims.itemName != null) {
  27789. hasNameEncode = true;
  27790. }
  27791. });
  27792. if (!hasNameEncode && firstCategoryDimIndex != null) {
  27793. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  27794. }
  27795. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  27796. var list = new List(dimInfoList, seriesModel);
  27797. list.setCalculationInfo(stackCalculationInfo);
  27798. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  27799. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  27800. // Use dataIndex as ordinal value in categoryAxis
  27801. return dimIndex === firstCategoryDimIndex
  27802. ? dataIndex
  27803. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  27804. }
  27805. : null;
  27806. list.hasItemOption = false;
  27807. list.initData(source, null, dimValueGetter);
  27808. return list;
  27809. }
  27810. function isNeedCompleteOrdinalData(source) {
  27811. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  27812. var sampleItem = firstDataNotNull(source.data || []);
  27813. return sampleItem != null
  27814. && !isArray(getDataItemValue(sampleItem));
  27815. }
  27816. }
  27817. function firstDataNotNull(data) {
  27818. var i = 0;
  27819. while (i < data.length && data[i] == null) {
  27820. i++;
  27821. }
  27822. return data[i];
  27823. }
  27824. /*
  27825. * Licensed to the Apache Software Foundation (ASF) under one
  27826. * or more contributor license agreements. See the NOTICE file
  27827. * distributed with this work for additional information
  27828. * regarding copyright ownership. The ASF licenses this file
  27829. * to you under the Apache License, Version 2.0 (the
  27830. * "License"); you may not use this file except in compliance
  27831. * with the License. You may obtain a copy of the License at
  27832. *
  27833. * http://www.apache.org/licenses/LICENSE-2.0
  27834. *
  27835. * Unless required by applicable law or agreed to in writing,
  27836. * software distributed under the License is distributed on an
  27837. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27838. * KIND, either express or implied. See the License for the
  27839. * specific language governing permissions and limitations
  27840. * under the License.
  27841. */
  27842. /**
  27843. * // Scale class management
  27844. * @module echarts/scale/Scale
  27845. */
  27846. /**
  27847. * @param {Object} [setting]
  27848. */
  27849. function Scale(setting) {
  27850. this._setting = setting || {};
  27851. /**
  27852. * Extent
  27853. * @type {Array.<number>}
  27854. * @protected
  27855. */
  27856. this._extent = [Infinity, -Infinity];
  27857. /**
  27858. * Step is calculated in adjustExtent
  27859. * @type {Array.<number>}
  27860. * @protected
  27861. */
  27862. this._interval = 0;
  27863. this.init && this.init.apply(this, arguments);
  27864. }
  27865. /**
  27866. * Parse input val to valid inner number.
  27867. * @param {*} val
  27868. * @return {number}
  27869. */
  27870. Scale.prototype.parse = function (val) {
  27871. // Notice: This would be a trap here, If the implementation
  27872. // of this method depends on extent, and this method is used
  27873. // before extent set (like in dataZoom), it would be wrong.
  27874. // Nevertheless, parse does not depend on extent generally.
  27875. return val;
  27876. };
  27877. Scale.prototype.getSetting = function (name) {
  27878. return this._setting[name];
  27879. };
  27880. Scale.prototype.contain = function (val) {
  27881. var extent = this._extent;
  27882. return val >= extent[0] && val <= extent[1];
  27883. };
  27884. /**
  27885. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  27886. * @param {number} val
  27887. * @return {number}
  27888. */
  27889. Scale.prototype.normalize = function (val) {
  27890. var extent = this._extent;
  27891. if (extent[1] === extent[0]) {
  27892. return 0.5;
  27893. }
  27894. return (val - extent[0]) / (extent[1] - extent[0]);
  27895. };
  27896. /**
  27897. * Scale normalized value
  27898. * @param {number} val
  27899. * @return {number}
  27900. */
  27901. Scale.prototype.scale = function (val) {
  27902. var extent = this._extent;
  27903. return val * (extent[1] - extent[0]) + extent[0];
  27904. };
  27905. /**
  27906. * Set extent from data
  27907. * @param {Array.<number>} other
  27908. */
  27909. Scale.prototype.unionExtent = function (other) {
  27910. var extent = this._extent;
  27911. other[0] < extent[0] && (extent[0] = other[0]);
  27912. other[1] > extent[1] && (extent[1] = other[1]);
  27913. // not setExtent because in log axis it may transformed to power
  27914. // this.setExtent(extent[0], extent[1]);
  27915. };
  27916. /**
  27917. * Set extent from data
  27918. * @param {module:echarts/data/List} data
  27919. * @param {string} dim
  27920. */
  27921. Scale.prototype.unionExtentFromData = function (data, dim) {
  27922. this.unionExtent(data.getApproximateExtent(dim));
  27923. };
  27924. /**
  27925. * Get extent
  27926. * @return {Array.<number>}
  27927. */
  27928. Scale.prototype.getExtent = function () {
  27929. return this._extent.slice();
  27930. };
  27931. /**
  27932. * Set extent
  27933. * @param {number} start
  27934. * @param {number} end
  27935. */
  27936. Scale.prototype.setExtent = function (start, end) {
  27937. var thisExtent = this._extent;
  27938. if (!isNaN(start)) {
  27939. thisExtent[0] = start;
  27940. }
  27941. if (!isNaN(end)) {
  27942. thisExtent[1] = end;
  27943. }
  27944. };
  27945. /**
  27946. * When axis extent depends on data and no data exists,
  27947. * axis ticks should not be drawn, which is named 'blank'.
  27948. */
  27949. Scale.prototype.isBlank = function () {
  27950. return this._isBlank;
  27951. },
  27952. /**
  27953. * When axis extent depends on data and no data exists,
  27954. * axis ticks should not be drawn, which is named 'blank'.
  27955. */
  27956. Scale.prototype.setBlank = function (isBlank) {
  27957. this._isBlank = isBlank;
  27958. };
  27959. /**
  27960. * @abstract
  27961. * @param {*} tick
  27962. * @return {string} label of the tick.
  27963. */
  27964. Scale.prototype.getLabel = null;
  27965. enableClassExtend(Scale);
  27966. enableClassManagement(Scale, {
  27967. registerWhenExtend: true
  27968. });
  27969. /*
  27970. * Licensed to the Apache Software Foundation (ASF) under one
  27971. * or more contributor license agreements. See the NOTICE file
  27972. * distributed with this work for additional information
  27973. * regarding copyright ownership. The ASF licenses this file
  27974. * to you under the Apache License, Version 2.0 (the
  27975. * "License"); you may not use this file except in compliance
  27976. * with the License. You may obtain a copy of the License at
  27977. *
  27978. * http://www.apache.org/licenses/LICENSE-2.0
  27979. *
  27980. * Unless required by applicable law or agreed to in writing,
  27981. * software distributed under the License is distributed on an
  27982. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27983. * KIND, either express or implied. See the License for the
  27984. * specific language governing permissions and limitations
  27985. * under the License.
  27986. */
  27987. /**
  27988. * @constructor
  27989. * @param {Object} [opt]
  27990. * @param {Object} [opt.categories=[]]
  27991. * @param {Object} [opt.needCollect=false]
  27992. * @param {Object} [opt.deduplication=false]
  27993. */
  27994. function OrdinalMeta(opt) {
  27995. /**
  27996. * @readOnly
  27997. * @type {Array.<string>}
  27998. */
  27999. this.categories = opt.categories || [];
  28000. /**
  28001. * @private
  28002. * @type {boolean}
  28003. */
  28004. this._needCollect = opt.needCollect;
  28005. /**
  28006. * @private
  28007. * @type {boolean}
  28008. */
  28009. this._deduplication = opt.deduplication;
  28010. /**
  28011. * @private
  28012. * @type {boolean}
  28013. */
  28014. this._map;
  28015. }
  28016. /**
  28017. * @param {module:echarts/model/Model} axisModel
  28018. * @return {module:echarts/data/OrdinalMeta}
  28019. */
  28020. OrdinalMeta.createByAxisModel = function (axisModel) {
  28021. var option = axisModel.option;
  28022. var data = option.data;
  28023. var categories = data && map(data, getName);
  28024. return new OrdinalMeta({
  28025. categories: categories,
  28026. needCollect: !categories,
  28027. // deduplication is default in axis.
  28028. deduplication: option.dedplication !== false
  28029. });
  28030. };
  28031. var proto$1 = OrdinalMeta.prototype;
  28032. /**
  28033. * @param {string} category
  28034. * @return {number} ordinal
  28035. */
  28036. proto$1.getOrdinal = function (category) {
  28037. return getOrCreateMap(this).get(category);
  28038. };
  28039. /**
  28040. * @param {*} category
  28041. * @return {number} The ordinal. If not found, return NaN.
  28042. */
  28043. proto$1.parseAndCollect = function (category) {
  28044. var index;
  28045. var needCollect = this._needCollect;
  28046. // The value of category dim can be the index of the given category set.
  28047. // This feature is only supported when !needCollect, because we should
  28048. // consider a common case: a value is 2017, which is a number but is
  28049. // expected to be tread as a category. This case usually happen in dataset,
  28050. // where it happent to be no need of the index feature.
  28051. if (typeof category !== 'string' && !needCollect) {
  28052. return category;
  28053. }
  28054. // Optimize for the scenario:
  28055. // category is ['2012-01-01', '2012-01-02', ...], where the input
  28056. // data has been ensured not duplicate and is large data.
  28057. // Notice, if a dataset dimension provide categroies, usually echarts
  28058. // should remove duplication except user tell echarts dont do that
  28059. // (set axis.deduplication = false), because echarts do not know whether
  28060. // the values in the category dimension has duplication (consider the
  28061. // parallel-aqi example)
  28062. if (needCollect && !this._deduplication) {
  28063. index = this.categories.length;
  28064. this.categories[index] = category;
  28065. return index;
  28066. }
  28067. var map$$1 = getOrCreateMap(this);
  28068. index = map$$1.get(category);
  28069. if (index == null) {
  28070. if (needCollect) {
  28071. index = this.categories.length;
  28072. this.categories[index] = category;
  28073. map$$1.set(category, index);
  28074. }
  28075. else {
  28076. index = NaN;
  28077. }
  28078. }
  28079. return index;
  28080. };
  28081. // Consider big data, do not create map until needed.
  28082. function getOrCreateMap(ordinalMeta) {
  28083. return ordinalMeta._map || (
  28084. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  28085. );
  28086. }
  28087. function getName(obj) {
  28088. if (isObject$1(obj) && obj.value != null) {
  28089. return obj.value;
  28090. }
  28091. else {
  28092. return obj + '';
  28093. }
  28094. }
  28095. /*
  28096. * Licensed to the Apache Software Foundation (ASF) under one
  28097. * or more contributor license agreements. See the NOTICE file
  28098. * distributed with this work for additional information
  28099. * regarding copyright ownership. The ASF licenses this file
  28100. * to you under the Apache License, Version 2.0 (the
  28101. * "License"); you may not use this file except in compliance
  28102. * with the License. You may obtain a copy of the License at
  28103. *
  28104. * http://www.apache.org/licenses/LICENSE-2.0
  28105. *
  28106. * Unless required by applicable law or agreed to in writing,
  28107. * software distributed under the License is distributed on an
  28108. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28109. * KIND, either express or implied. See the License for the
  28110. * specific language governing permissions and limitations
  28111. * under the License.
  28112. */
  28113. /**
  28114. * Linear continuous scale
  28115. * @module echarts/coord/scale/Ordinal
  28116. *
  28117. * http://en.wikipedia.org/wiki/Level_of_measurement
  28118. */
  28119. // FIXME only one data
  28120. var scaleProto = Scale.prototype;
  28121. var OrdinalScale = Scale.extend({
  28122. type: 'ordinal',
  28123. /**
  28124. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  28125. */
  28126. init: function (ordinalMeta, extent) {
  28127. // Caution: Should not use instanceof, consider ec-extensions using
  28128. // import approach to get OrdinalMeta class.
  28129. if (!ordinalMeta || isArray(ordinalMeta)) {
  28130. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  28131. }
  28132. this._ordinalMeta = ordinalMeta;
  28133. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  28134. },
  28135. parse: function (val) {
  28136. return typeof val === 'string'
  28137. ? this._ordinalMeta.getOrdinal(val)
  28138. // val might be float.
  28139. : Math.round(val);
  28140. },
  28141. contain: function (rank) {
  28142. rank = this.parse(rank);
  28143. return scaleProto.contain.call(this, rank)
  28144. && this._ordinalMeta.categories[rank] != null;
  28145. },
  28146. /**
  28147. * Normalize given rank or name to linear [0, 1]
  28148. * @param {number|string} [val]
  28149. * @return {number}
  28150. */
  28151. normalize: function (val) {
  28152. return scaleProto.normalize.call(this, this.parse(val));
  28153. },
  28154. scale: function (val) {
  28155. return Math.round(scaleProto.scale.call(this, val));
  28156. },
  28157. /**
  28158. * @return {Array}
  28159. */
  28160. getTicks: function () {
  28161. var ticks = [];
  28162. var extent = this._extent;
  28163. var rank = extent[0];
  28164. while (rank <= extent[1]) {
  28165. ticks.push(rank);
  28166. rank++;
  28167. }
  28168. return ticks;
  28169. },
  28170. /**
  28171. * Get item on rank n
  28172. * @param {number} n
  28173. * @return {string}
  28174. */
  28175. getLabel: function (n) {
  28176. if (!this.isBlank()) {
  28177. // Note that if no data, ordinalMeta.categories is an empty array.
  28178. return this._ordinalMeta.categories[n];
  28179. }
  28180. },
  28181. /**
  28182. * @return {number}
  28183. */
  28184. count: function () {
  28185. return this._extent[1] - this._extent[0] + 1;
  28186. },
  28187. /**
  28188. * @override
  28189. */
  28190. unionExtentFromData: function (data, dim) {
  28191. this.unionExtent(data.getApproximateExtent(dim));
  28192. },
  28193. getOrdinalMeta: function () {
  28194. return this._ordinalMeta;
  28195. },
  28196. niceTicks: noop,
  28197. niceExtent: noop
  28198. });
  28199. /**
  28200. * @return {module:echarts/scale/Time}
  28201. */
  28202. OrdinalScale.create = function () {
  28203. return new OrdinalScale();
  28204. };
  28205. /*
  28206. * Licensed to the Apache Software Foundation (ASF) under one
  28207. * or more contributor license agreements. See the NOTICE file
  28208. * distributed with this work for additional information
  28209. * regarding copyright ownership. The ASF licenses this file
  28210. * to you under the Apache License, Version 2.0 (the
  28211. * "License"); you may not use this file except in compliance
  28212. * with the License. You may obtain a copy of the License at
  28213. *
  28214. * http://www.apache.org/licenses/LICENSE-2.0
  28215. *
  28216. * Unless required by applicable law or agreed to in writing,
  28217. * software distributed under the License is distributed on an
  28218. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28219. * KIND, either express or implied. See the License for the
  28220. * specific language governing permissions and limitations
  28221. * under the License.
  28222. */
  28223. /**
  28224. * For testable.
  28225. */
  28226. var roundNumber$1 = round$2;
  28227. /**
  28228. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  28229. * Should be extent[0] < extent[1].
  28230. * @param {number} splitNumber splitNumber should be >= 1.
  28231. * @param {number} [minInterval]
  28232. * @param {number} [maxInterval]
  28233. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  28234. */
  28235. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  28236. var result = {};
  28237. var span = extent[1] - extent[0];
  28238. var interval = result.interval = nice(span / splitNumber, true);
  28239. if (minInterval != null && interval < minInterval) {
  28240. interval = result.interval = minInterval;
  28241. }
  28242. if (maxInterval != null && interval > maxInterval) {
  28243. interval = result.interval = maxInterval;
  28244. }
  28245. // Tow more digital for tick.
  28246. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  28247. // Niced extent inside original extent
  28248. var niceTickExtent = result.niceTickExtent = [
  28249. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  28250. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  28251. ];
  28252. fixExtent(niceTickExtent, extent);
  28253. return result;
  28254. }
  28255. /**
  28256. * @param {number} interval
  28257. * @return {number} interval precision
  28258. */
  28259. function getIntervalPrecision(interval) {
  28260. // Tow more digital for tick.
  28261. return getPrecisionSafe(interval) + 2;
  28262. }
  28263. function clamp(niceTickExtent, idx, extent) {
  28264. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  28265. }
  28266. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  28267. function fixExtent(niceTickExtent, extent) {
  28268. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  28269. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  28270. clamp(niceTickExtent, 0, extent);
  28271. clamp(niceTickExtent, 1, extent);
  28272. if (niceTickExtent[0] > niceTickExtent[1]) {
  28273. niceTickExtent[0] = niceTickExtent[1];
  28274. }
  28275. }
  28276. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  28277. var ticks = [];
  28278. // If interval is 0, return [];
  28279. if (!interval) {
  28280. return ticks;
  28281. }
  28282. // Consider this case: using dataZoom toolbox, zoom and zoom.
  28283. var safeLimit = 10000;
  28284. if (extent[0] < niceTickExtent[0]) {
  28285. ticks.push(extent[0]);
  28286. }
  28287. var tick = niceTickExtent[0];
  28288. while (tick <= niceTickExtent[1]) {
  28289. ticks.push(tick);
  28290. // Avoid rounding error
  28291. tick = roundNumber$1(tick + interval, intervalPrecision);
  28292. if (tick === ticks[ticks.length - 1]) {
  28293. // Consider out of safe float point, e.g.,
  28294. // -3711126.9907707 + 2e-10 === -3711126.9907707
  28295. break;
  28296. }
  28297. if (ticks.length > safeLimit) {
  28298. return [];
  28299. }
  28300. }
  28301. // Consider this case: the last item of ticks is smaller
  28302. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  28303. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  28304. ticks.push(extent[1]);
  28305. }
  28306. return ticks;
  28307. }
  28308. /*
  28309. * Licensed to the Apache Software Foundation (ASF) under one
  28310. * or more contributor license agreements. See the NOTICE file
  28311. * distributed with this work for additional information
  28312. * regarding copyright ownership. The ASF licenses this file
  28313. * to you under the Apache License, Version 2.0 (the
  28314. * "License"); you may not use this file except in compliance
  28315. * with the License. You may obtain a copy of the License at
  28316. *
  28317. * http://www.apache.org/licenses/LICENSE-2.0
  28318. *
  28319. * Unless required by applicable law or agreed to in writing,
  28320. * software distributed under the License is distributed on an
  28321. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28322. * KIND, either express or implied. See the License for the
  28323. * specific language governing permissions and limitations
  28324. * under the License.
  28325. */
  28326. /**
  28327. * Interval scale
  28328. * @module echarts/scale/Interval
  28329. */
  28330. var roundNumber = round$2;
  28331. /**
  28332. * @alias module:echarts/coord/scale/Interval
  28333. * @constructor
  28334. */
  28335. var IntervalScale = Scale.extend({
  28336. type: 'interval',
  28337. _interval: 0,
  28338. _intervalPrecision: 2,
  28339. setExtent: function (start, end) {
  28340. var thisExtent = this._extent;
  28341. //start,end may be a Number like '25',so...
  28342. if (!isNaN(start)) {
  28343. thisExtent[0] = parseFloat(start);
  28344. }
  28345. if (!isNaN(end)) {
  28346. thisExtent[1] = parseFloat(end);
  28347. }
  28348. },
  28349. unionExtent: function (other) {
  28350. var extent = this._extent;
  28351. other[0] < extent[0] && (extent[0] = other[0]);
  28352. other[1] > extent[1] && (extent[1] = other[1]);
  28353. // unionExtent may called by it's sub classes
  28354. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  28355. },
  28356. /**
  28357. * Get interval
  28358. */
  28359. getInterval: function () {
  28360. return this._interval;
  28361. },
  28362. /**
  28363. * Set interval
  28364. */
  28365. setInterval: function (interval) {
  28366. this._interval = interval;
  28367. // Dropped auto calculated niceExtent and use user setted extent
  28368. // We assume user wan't to set both interval, min, max to get a better result
  28369. this._niceExtent = this._extent.slice();
  28370. this._intervalPrecision = getIntervalPrecision(interval);
  28371. },
  28372. /**
  28373. * @return {Array.<number>}
  28374. */
  28375. getTicks: function () {
  28376. return intervalScaleGetTicks(
  28377. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  28378. );
  28379. },
  28380. /**
  28381. * @param {number} data
  28382. * @param {Object} [opt]
  28383. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  28384. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  28385. * @return {string}
  28386. */
  28387. getLabel: function (data, opt) {
  28388. if (data == null) {
  28389. return '';
  28390. }
  28391. var precision = opt && opt.precision;
  28392. if (precision == null) {
  28393. precision = getPrecisionSafe(data) || 0;
  28394. }
  28395. else if (precision === 'auto') {
  28396. // Should be more precise then tick.
  28397. precision = this._intervalPrecision;
  28398. }
  28399. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  28400. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  28401. data = roundNumber(data, precision, true);
  28402. return addCommas(data);
  28403. },
  28404. /**
  28405. * Update interval and extent of intervals for nice ticks
  28406. *
  28407. * @param {number} [splitNumber = 5] Desired number of ticks
  28408. * @param {number} [minInterval]
  28409. * @param {number} [maxInterval]
  28410. */
  28411. niceTicks: function (splitNumber, minInterval, maxInterval) {
  28412. splitNumber = splitNumber || 5;
  28413. var extent = this._extent;
  28414. var span = extent[1] - extent[0];
  28415. if (!isFinite(span)) {
  28416. return;
  28417. }
  28418. // User may set axis min 0 and data are all negative
  28419. // FIXME If it needs to reverse ?
  28420. if (span < 0) {
  28421. span = -span;
  28422. extent.reverse();
  28423. }
  28424. var result = intervalScaleNiceTicks(
  28425. extent, splitNumber, minInterval, maxInterval
  28426. );
  28427. this._intervalPrecision = result.intervalPrecision;
  28428. this._interval = result.interval;
  28429. this._niceExtent = result.niceTickExtent;
  28430. },
  28431. /**
  28432. * Nice extent.
  28433. * @param {Object} opt
  28434. * @param {number} [opt.splitNumber = 5] Given approx tick number
  28435. * @param {boolean} [opt.fixMin=false]
  28436. * @param {boolean} [opt.fixMax=false]
  28437. * @param {boolean} [opt.minInterval]
  28438. * @param {boolean} [opt.maxInterval]
  28439. */
  28440. niceExtent: function (opt) {
  28441. var extent = this._extent;
  28442. // If extent start and end are same, expand them
  28443. if (extent[0] === extent[1]) {
  28444. if (extent[0] !== 0) {
  28445. // Expand extent
  28446. var expandSize = extent[0];
  28447. // In the fowllowing case
  28448. // Axis has been fixed max 100
  28449. // Plus data are all 100 and axis extent are [100, 100].
  28450. // Extend to the both side will cause expanded max is larger than fixed max.
  28451. // So only expand to the smaller side.
  28452. if (!opt.fixMax) {
  28453. extent[1] += expandSize / 2;
  28454. extent[0] -= expandSize / 2;
  28455. }
  28456. else {
  28457. extent[0] -= expandSize / 2;
  28458. }
  28459. }
  28460. else {
  28461. extent[1] = 1;
  28462. }
  28463. }
  28464. var span = extent[1] - extent[0];
  28465. // If there are no data and extent are [Infinity, -Infinity]
  28466. if (!isFinite(span)) {
  28467. extent[0] = 0;
  28468. extent[1] = 1;
  28469. }
  28470. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  28471. // var extent = this._extent;
  28472. var interval = this._interval;
  28473. if (!opt.fixMin) {
  28474. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  28475. }
  28476. if (!opt.fixMax) {
  28477. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  28478. }
  28479. }
  28480. });
  28481. /**
  28482. * @return {module:echarts/scale/Time}
  28483. */
  28484. IntervalScale.create = function () {
  28485. return new IntervalScale();
  28486. };
  28487. /*
  28488. * Licensed to the Apache Software Foundation (ASF) under one
  28489. * or more contributor license agreements. See the NOTICE file
  28490. * distributed with this work for additional information
  28491. * regarding copyright ownership. The ASF licenses this file
  28492. * to you under the Apache License, Version 2.0 (the
  28493. * "License"); you may not use this file except in compliance
  28494. * with the License. You may obtain a copy of the License at
  28495. *
  28496. * http://www.apache.org/licenses/LICENSE-2.0
  28497. *
  28498. * Unless required by applicable law or agreed to in writing,
  28499. * software distributed under the License is distributed on an
  28500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28501. * KIND, either express or implied. See the License for the
  28502. * specific language governing permissions and limitations
  28503. * under the License.
  28504. */
  28505. /* global Float32Array */
  28506. var STACK_PREFIX = '__ec_stack_';
  28507. var LARGE_BAR_MIN_WIDTH = 0.5;
  28508. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  28509. function getSeriesStackId(seriesModel) {
  28510. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  28511. }
  28512. function getAxisKey(axis) {
  28513. return axis.dim + axis.index;
  28514. }
  28515. /**
  28516. * @param {Object} opt
  28517. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  28518. * @param {number} opt.count Positive interger.
  28519. * @param {number} [opt.barWidth]
  28520. * @param {number} [opt.barMaxWidth]
  28521. * @param {number} [opt.barGap]
  28522. * @param {number} [opt.barCategoryGap]
  28523. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  28524. */
  28525. function getLayoutOnAxis(opt) {
  28526. var params = [];
  28527. var baseAxis = opt.axis;
  28528. var axisKey = 'axis0';
  28529. if (baseAxis.type !== 'category') {
  28530. return;
  28531. }
  28532. var bandWidth = baseAxis.getBandWidth();
  28533. for (var i = 0; i < opt.count || 0; i++) {
  28534. params.push(defaults({
  28535. bandWidth: bandWidth,
  28536. axisKey: axisKey,
  28537. stackId: STACK_PREFIX + i
  28538. }, opt));
  28539. }
  28540. var widthAndOffsets = doCalBarWidthAndOffset(params);
  28541. var result = [];
  28542. for (var i = 0; i < opt.count; i++) {
  28543. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  28544. item.offsetCenter = item.offset + item.width / 2;
  28545. result.push(item);
  28546. }
  28547. return result;
  28548. }
  28549. function prepareLayoutBarSeries(seriesType, ecModel) {
  28550. var seriesModels = [];
  28551. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  28552. // Check series coordinate, do layout for cartesian2d only
  28553. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  28554. seriesModels.push(seriesModel);
  28555. }
  28556. });
  28557. return seriesModels;
  28558. }
  28559. function makeColumnLayout(barSeries) {
  28560. var seriesInfoList = [];
  28561. each$1(barSeries, function (seriesModel) {
  28562. var data = seriesModel.getData();
  28563. var cartesian = seriesModel.coordinateSystem;
  28564. var baseAxis = cartesian.getBaseAxis();
  28565. var axisExtent = baseAxis.getExtent();
  28566. var bandWidth = baseAxis.type === 'category'
  28567. ? baseAxis.getBandWidth()
  28568. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  28569. var barWidth = parsePercent$1(
  28570. seriesModel.get('barWidth'), bandWidth
  28571. );
  28572. var barMaxWidth = parsePercent$1(
  28573. seriesModel.get('barMaxWidth'), bandWidth
  28574. );
  28575. var barGap = seriesModel.get('barGap');
  28576. var barCategoryGap = seriesModel.get('barCategoryGap');
  28577. seriesInfoList.push({
  28578. bandWidth: bandWidth,
  28579. barWidth: barWidth,
  28580. barMaxWidth: barMaxWidth,
  28581. barGap: barGap,
  28582. barCategoryGap: barCategoryGap,
  28583. axisKey: getAxisKey(baseAxis),
  28584. stackId: getSeriesStackId(seriesModel)
  28585. });
  28586. });
  28587. return doCalBarWidthAndOffset(seriesInfoList);
  28588. }
  28589. function doCalBarWidthAndOffset(seriesInfoList) {
  28590. // Columns info on each category axis. Key is cartesian name
  28591. var columnsMap = {};
  28592. each$1(seriesInfoList, function (seriesInfo, idx) {
  28593. var axisKey = seriesInfo.axisKey;
  28594. var bandWidth = seriesInfo.bandWidth;
  28595. var columnsOnAxis = columnsMap[axisKey] || {
  28596. bandWidth: bandWidth,
  28597. remainedWidth: bandWidth,
  28598. autoWidthCount: 0,
  28599. categoryGap: '20%',
  28600. gap: '30%',
  28601. stacks: {}
  28602. };
  28603. var stacks = columnsOnAxis.stacks;
  28604. columnsMap[axisKey] = columnsOnAxis;
  28605. var stackId = seriesInfo.stackId;
  28606. if (!stacks[stackId]) {
  28607. columnsOnAxis.autoWidthCount++;
  28608. }
  28609. stacks[stackId] = stacks[stackId] || {
  28610. width: 0,
  28611. maxWidth: 0
  28612. };
  28613. // Caution: In a single coordinate system, these barGrid attributes
  28614. // will be shared by series. Consider that they have default values,
  28615. // only the attributes set on the last series will work.
  28616. // Do not change this fact unless there will be a break change.
  28617. // TODO
  28618. var barWidth = seriesInfo.barWidth;
  28619. if (barWidth && !stacks[stackId].width) {
  28620. // See #6312, do not restrict width.
  28621. stacks[stackId].width = barWidth;
  28622. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  28623. columnsOnAxis.remainedWidth -= barWidth;
  28624. }
  28625. var barMaxWidth = seriesInfo.barMaxWidth;
  28626. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  28627. var barGap = seriesInfo.barGap;
  28628. (barGap != null) && (columnsOnAxis.gap = barGap);
  28629. var barCategoryGap = seriesInfo.barCategoryGap;
  28630. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  28631. });
  28632. var result = {};
  28633. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  28634. result[coordSysName] = {};
  28635. var stacks = columnsOnAxis.stacks;
  28636. var bandWidth = columnsOnAxis.bandWidth;
  28637. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  28638. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  28639. var remainedWidth = columnsOnAxis.remainedWidth;
  28640. var autoWidthCount = columnsOnAxis.autoWidthCount;
  28641. var autoWidth = (remainedWidth - categoryGap)
  28642. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  28643. autoWidth = Math.max(autoWidth, 0);
  28644. // Find if any auto calculated bar exceeded maxBarWidth
  28645. each$1(stacks, function (column, stack) {
  28646. var maxWidth = column.maxWidth;
  28647. if (maxWidth && maxWidth < autoWidth) {
  28648. maxWidth = Math.min(maxWidth, remainedWidth);
  28649. if (column.width) {
  28650. maxWidth = Math.min(maxWidth, column.width);
  28651. }
  28652. remainedWidth -= maxWidth;
  28653. column.width = maxWidth;
  28654. autoWidthCount--;
  28655. }
  28656. });
  28657. // Recalculate width again
  28658. autoWidth = (remainedWidth - categoryGap)
  28659. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  28660. autoWidth = Math.max(autoWidth, 0);
  28661. var widthSum = 0;
  28662. var lastColumn;
  28663. each$1(stacks, function (column, idx) {
  28664. if (!column.width) {
  28665. column.width = autoWidth;
  28666. }
  28667. lastColumn = column;
  28668. widthSum += column.width * (1 + barGapPercent);
  28669. });
  28670. if (lastColumn) {
  28671. widthSum -= lastColumn.width * barGapPercent;
  28672. }
  28673. var offset = -widthSum / 2;
  28674. each$1(stacks, function (column, stackId) {
  28675. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  28676. offset: offset,
  28677. width: column.width
  28678. };
  28679. offset += column.width * (1 + barGapPercent);
  28680. });
  28681. });
  28682. return result;
  28683. }
  28684. /**
  28685. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  28686. * @param {module:echarts/coord/Axis} axis
  28687. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  28688. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  28689. */
  28690. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  28691. if (barWidthAndOffset && axis) {
  28692. var result = barWidthAndOffset[getAxisKey(axis)];
  28693. if (result != null && seriesModel != null) {
  28694. result = result[getSeriesStackId(seriesModel)];
  28695. }
  28696. return result;
  28697. }
  28698. }
  28699. /**
  28700. * @param {string} seriesType
  28701. * @param {module:echarts/model/Global} ecModel
  28702. */
  28703. function layout(seriesType, ecModel) {
  28704. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  28705. var barWidthAndOffset = makeColumnLayout(seriesModels);
  28706. var lastStackCoords = {};
  28707. each$1(seriesModels, function (seriesModel) {
  28708. var data = seriesModel.getData();
  28709. var cartesian = seriesModel.coordinateSystem;
  28710. var baseAxis = cartesian.getBaseAxis();
  28711. var stackId = getSeriesStackId(seriesModel);
  28712. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  28713. var columnOffset = columnLayoutInfo.offset;
  28714. var columnWidth = columnLayoutInfo.width;
  28715. var valueAxis = cartesian.getOtherAxis(baseAxis);
  28716. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  28717. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  28718. data.setLayout({
  28719. offset: columnOffset,
  28720. size: columnWidth
  28721. });
  28722. var valueDim = data.mapDimension(valueAxis.dim);
  28723. var baseDim = data.mapDimension(baseAxis.dim);
  28724. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  28725. var isValueAxisH = valueAxis.isHorizontal();
  28726. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  28727. for (var idx = 0, len = data.count(); idx < len; idx++) {
  28728. var value = data.get(valueDim, idx);
  28729. var baseValue = data.get(baseDim, idx);
  28730. if (isNaN(value)) {
  28731. continue;
  28732. }
  28733. var sign = value >= 0 ? 'p' : 'n';
  28734. var baseCoord = valueAxisStart;
  28735. // Because of the barMinHeight, we can not use the value in
  28736. // stackResultDimension directly.
  28737. if (stacked) {
  28738. // Only ordinal axis can be stacked.
  28739. if (!lastStackCoords[stackId][baseValue]) {
  28740. lastStackCoords[stackId][baseValue] = {
  28741. p: valueAxisStart, // Positive stack
  28742. n: valueAxisStart // Negative stack
  28743. };
  28744. }
  28745. // Should also consider #4243
  28746. baseCoord = lastStackCoords[stackId][baseValue][sign];
  28747. }
  28748. var x;
  28749. var y;
  28750. var width;
  28751. var height;
  28752. if (isValueAxisH) {
  28753. var coord = cartesian.dataToPoint([value, baseValue]);
  28754. x = baseCoord;
  28755. y = coord[1] + columnOffset;
  28756. width = coord[0] - valueAxisStart;
  28757. height = columnWidth;
  28758. if (Math.abs(width) < barMinHeight) {
  28759. width = (width < 0 ? -1 : 1) * barMinHeight;
  28760. }
  28761. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  28762. }
  28763. else {
  28764. var coord = cartesian.dataToPoint([baseValue, value]);
  28765. x = coord[0] + columnOffset;
  28766. y = baseCoord;
  28767. width = columnWidth;
  28768. height = coord[1] - valueAxisStart;
  28769. if (Math.abs(height) < barMinHeight) {
  28770. // Include zero to has a positive bar
  28771. height = (height <= 0 ? -1 : 1) * barMinHeight;
  28772. }
  28773. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  28774. }
  28775. data.setItemLayout(idx, {
  28776. x: x,
  28777. y: y,
  28778. width: width,
  28779. height: height
  28780. });
  28781. }
  28782. }, this);
  28783. }
  28784. // TODO: Do not support stack in large mode yet.
  28785. var largeLayout = {
  28786. seriesType: 'bar',
  28787. plan: createRenderPlanner(),
  28788. reset: function (seriesModel) {
  28789. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  28790. return;
  28791. }
  28792. var data = seriesModel.getData();
  28793. var cartesian = seriesModel.coordinateSystem;
  28794. var baseAxis = cartesian.getBaseAxis();
  28795. var valueAxis = cartesian.getOtherAxis(baseAxis);
  28796. var valueDim = data.mapDimension(valueAxis.dim);
  28797. var baseDim = data.mapDimension(baseAxis.dim);
  28798. var valueAxisHorizontal = valueAxis.isHorizontal();
  28799. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  28800. var barWidth = retrieveColumnLayout(
  28801. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  28802. ).width;
  28803. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  28804. barWidth = LARGE_BAR_MIN_WIDTH;
  28805. }
  28806. return {progress: progress};
  28807. function progress(params, data) {
  28808. var largePoints = new LargeArr(params.count * 2);
  28809. var dataIndex;
  28810. var coord = [];
  28811. var valuePair = [];
  28812. var offset = 0;
  28813. while ((dataIndex = params.next()) != null) {
  28814. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  28815. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  28816. coord = cartesian.dataToPoint(valuePair, null, coord);
  28817. largePoints[offset++] = coord[0];
  28818. largePoints[offset++] = coord[1];
  28819. }
  28820. data.setLayout({
  28821. largePoints: largePoints,
  28822. barWidth: barWidth,
  28823. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  28824. valueAxisHorizontal: valueAxisHorizontal
  28825. });
  28826. }
  28827. }
  28828. };
  28829. function isOnCartesian(seriesModel) {
  28830. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  28831. }
  28832. function isInLargeMode(seriesModel) {
  28833. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  28834. }
  28835. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  28836. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  28837. var extent = valueAxis.getGlobalExtent();
  28838. var min;
  28839. var max;
  28840. if (extent[0] > extent[1]) {
  28841. min = extent[1];
  28842. max = extent[0];
  28843. }
  28844. else {
  28845. min = extent[0];
  28846. max = extent[1];
  28847. }
  28848. var valueStart = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  28849. valueStart < min && (valueStart = min);
  28850. valueStart > max && (valueStart = max);
  28851. return valueStart;
  28852. }
  28853. /*
  28854. * Licensed to the Apache Software Foundation (ASF) under one
  28855. * or more contributor license agreements. See the NOTICE file
  28856. * distributed with this work for additional information
  28857. * regarding copyright ownership. The ASF licenses this file
  28858. * to you under the Apache License, Version 2.0 (the
  28859. * "License"); you may not use this file except in compliance
  28860. * with the License. You may obtain a copy of the License at
  28861. *
  28862. * http://www.apache.org/licenses/LICENSE-2.0
  28863. *
  28864. * Unless required by applicable law or agreed to in writing,
  28865. * software distributed under the License is distributed on an
  28866. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28867. * KIND, either express or implied. See the License for the
  28868. * specific language governing permissions and limitations
  28869. * under the License.
  28870. */
  28871. /*
  28872. * A third-party license is embeded for some of the code in this file:
  28873. * The "scaleLevels" was originally copied from "d3.js" with some
  28874. * modifications made for this project.
  28875. * (See more details in the comment on the definition of "scaleLevels" below.)
  28876. * The use of the source code of this file is also subject to the terms
  28877. * and consitions of the license of "d3.js" (BSD-3Clause, see
  28878. * </licenses/LICENSE-d3>).
  28879. */
  28880. // [About UTC and local time zone]:
  28881. // In most cases, `number.parseDate` will treat input data string as local time
  28882. // (except time zone is specified in time string). And `format.formateTime` returns
  28883. // local time by default. option.useUTC is false by default. This design have
  28884. // concidered these common case:
  28885. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  28886. // in local time by default.
  28887. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  28888. // as its original time, without any time difference.
  28889. var intervalScaleProto = IntervalScale.prototype;
  28890. var mathCeil = Math.ceil;
  28891. var mathFloor = Math.floor;
  28892. var ONE_SECOND = 1000;
  28893. var ONE_MINUTE = ONE_SECOND * 60;
  28894. var ONE_HOUR = ONE_MINUTE * 60;
  28895. var ONE_DAY = ONE_HOUR * 24;
  28896. // FIXME 公用?
  28897. var bisect = function (a, x, lo, hi) {
  28898. while (lo < hi) {
  28899. var mid = lo + hi >>> 1;
  28900. if (a[mid][1] < x) {
  28901. lo = mid + 1;
  28902. }
  28903. else {
  28904. hi = mid;
  28905. }
  28906. }
  28907. return lo;
  28908. };
  28909. /**
  28910. * @alias module:echarts/coord/scale/Time
  28911. * @constructor
  28912. */
  28913. var TimeScale = IntervalScale.extend({
  28914. type: 'time',
  28915. /**
  28916. * @override
  28917. */
  28918. getLabel: function (val) {
  28919. var stepLvl = this._stepLvl;
  28920. var date = new Date(val);
  28921. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  28922. },
  28923. /**
  28924. * @override
  28925. */
  28926. niceExtent: function (opt) {
  28927. var extent = this._extent;
  28928. // If extent start and end are same, expand them
  28929. if (extent[0] === extent[1]) {
  28930. // Expand extent
  28931. extent[0] -= ONE_DAY;
  28932. extent[1] += ONE_DAY;
  28933. }
  28934. // If there are no data and extent are [Infinity, -Infinity]
  28935. if (extent[1] === -Infinity && extent[0] === Infinity) {
  28936. var d = new Date();
  28937. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  28938. extent[0] = extent[1] - ONE_DAY;
  28939. }
  28940. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  28941. // var extent = this._extent;
  28942. var interval = this._interval;
  28943. if (!opt.fixMin) {
  28944. extent[0] = round$2(mathFloor(extent[0] / interval) * interval);
  28945. }
  28946. if (!opt.fixMax) {
  28947. extent[1] = round$2(mathCeil(extent[1] / interval) * interval);
  28948. }
  28949. },
  28950. /**
  28951. * @override
  28952. */
  28953. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  28954. approxTickNum = approxTickNum || 10;
  28955. var extent = this._extent;
  28956. var span = extent[1] - extent[0];
  28957. var approxInterval = span / approxTickNum;
  28958. if (minInterval != null && approxInterval < minInterval) {
  28959. approxInterval = minInterval;
  28960. }
  28961. if (maxInterval != null && approxInterval > maxInterval) {
  28962. approxInterval = maxInterval;
  28963. }
  28964. var scaleLevelsLen = scaleLevels.length;
  28965. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  28966. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  28967. var interval = level[1];
  28968. // Same with interval scale if span is much larger than 1 year
  28969. if (level[0] === 'year') {
  28970. var yearSpan = span / interval;
  28971. // From "Nice Numbers for Graph Labels" of Graphic Gems
  28972. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  28973. var yearStep = nice(yearSpan / approxTickNum, true);
  28974. interval *= yearStep;
  28975. }
  28976. var timezoneOffset = this.getSetting('useUTC')
  28977. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  28978. var niceExtent = [
  28979. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  28980. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  28981. ];
  28982. fixExtent(niceExtent, extent);
  28983. this._stepLvl = level;
  28984. // Interval will be used in getTicks
  28985. this._interval = interval;
  28986. this._niceExtent = niceExtent;
  28987. },
  28988. parse: function (val) {
  28989. // val might be float.
  28990. return +parseDate(val);
  28991. }
  28992. });
  28993. each$1(['contain', 'normalize'], function (methodName) {
  28994. TimeScale.prototype[methodName] = function (val) {
  28995. return intervalScaleProto[methodName].call(this, this.parse(val));
  28996. };
  28997. });
  28998. /**
  28999. * This implementation was originally copied from "d3.js"
  29000. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  29001. * with some modifications made for this program.
  29002. * See the license statement at the head of this file.
  29003. */
  29004. var scaleLevels = [
  29005. // Format interval
  29006. ['hh:mm:ss', ONE_SECOND], // 1s
  29007. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  29008. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  29009. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  29010. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  29011. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  29012. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  29013. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  29014. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  29015. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  29016. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  29017. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  29018. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  29019. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  29020. ['MM-dd\nyyyy', ONE_DAY], // 1d
  29021. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  29022. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  29023. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  29024. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  29025. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  29026. ['week', ONE_DAY * 7], // 7d
  29027. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  29028. ['week', ONE_DAY * 14], // 2w
  29029. ['week', ONE_DAY * 21], // 3w
  29030. ['month', ONE_DAY * 31], // 1M
  29031. ['week', ONE_DAY * 42], // 6w
  29032. ['month', ONE_DAY * 62], // 2M
  29033. ['week', ONE_DAY * 70], // 10w
  29034. ['quarter', ONE_DAY * 95], // 3M
  29035. ['month', ONE_DAY * 31 * 4], // 4M
  29036. ['month', ONE_DAY * 31 * 5], // 5M
  29037. ['half-year', ONE_DAY * 380 / 2], // 6M
  29038. ['month', ONE_DAY * 31 * 8], // 8M
  29039. ['month', ONE_DAY * 31 * 10], // 10M
  29040. ['year', ONE_DAY * 380] // 1Y
  29041. ];
  29042. /**
  29043. * @param {module:echarts/model/Model}
  29044. * @return {module:echarts/scale/Time}
  29045. */
  29046. TimeScale.create = function (model) {
  29047. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  29048. };
  29049. /*
  29050. * Licensed to the Apache Software Foundation (ASF) under one
  29051. * or more contributor license agreements. See the NOTICE file
  29052. * distributed with this work for additional information
  29053. * regarding copyright ownership. The ASF licenses this file
  29054. * to you under the Apache License, Version 2.0 (the
  29055. * "License"); you may not use this file except in compliance
  29056. * with the License. You may obtain a copy of the License at
  29057. *
  29058. * http://www.apache.org/licenses/LICENSE-2.0
  29059. *
  29060. * Unless required by applicable law or agreed to in writing,
  29061. * software distributed under the License is distributed on an
  29062. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29063. * KIND, either express or implied. See the License for the
  29064. * specific language governing permissions and limitations
  29065. * under the License.
  29066. */
  29067. /**
  29068. * Log scale
  29069. * @module echarts/scale/Log
  29070. */
  29071. // Use some method of IntervalScale
  29072. var scaleProto$1 = Scale.prototype;
  29073. var intervalScaleProto$1 = IntervalScale.prototype;
  29074. var getPrecisionSafe$1 = getPrecisionSafe;
  29075. var roundingErrorFix = round$2;
  29076. var mathFloor$1 = Math.floor;
  29077. var mathCeil$1 = Math.ceil;
  29078. var mathPow$1 = Math.pow;
  29079. var mathLog = Math.log;
  29080. var LogScale = Scale.extend({
  29081. type: 'log',
  29082. base: 10,
  29083. $constructor: function () {
  29084. Scale.apply(this, arguments);
  29085. this._originalScale = new IntervalScale();
  29086. },
  29087. /**
  29088. * @return {Array.<number>}
  29089. */
  29090. getTicks: function () {
  29091. var originalScale = this._originalScale;
  29092. var extent = this._extent;
  29093. var originalExtent = originalScale.getExtent();
  29094. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  29095. var powVal = round$2(mathPow$1(this.base, val));
  29096. // Fix #4158
  29097. powVal = (val === extent[0] && originalScale.__fixMin)
  29098. ? fixRoundingError(powVal, originalExtent[0])
  29099. : powVal;
  29100. powVal = (val === extent[1] && originalScale.__fixMax)
  29101. ? fixRoundingError(powVal, originalExtent[1])
  29102. : powVal;
  29103. return powVal;
  29104. }, this);
  29105. },
  29106. /**
  29107. * @param {number} val
  29108. * @return {string}
  29109. */
  29110. getLabel: intervalScaleProto$1.getLabel,
  29111. /**
  29112. * @param {number} val
  29113. * @return {number}
  29114. */
  29115. scale: function (val) {
  29116. val = scaleProto$1.scale.call(this, val);
  29117. return mathPow$1(this.base, val);
  29118. },
  29119. /**
  29120. * @param {number} start
  29121. * @param {number} end
  29122. */
  29123. setExtent: function (start, end) {
  29124. var base = this.base;
  29125. start = mathLog(start) / mathLog(base);
  29126. end = mathLog(end) / mathLog(base);
  29127. intervalScaleProto$1.setExtent.call(this, start, end);
  29128. },
  29129. /**
  29130. * @return {number} end
  29131. */
  29132. getExtent: function () {
  29133. var base = this.base;
  29134. var extent = scaleProto$1.getExtent.call(this);
  29135. extent[0] = mathPow$1(base, extent[0]);
  29136. extent[1] = mathPow$1(base, extent[1]);
  29137. // Fix #4158
  29138. var originalScale = this._originalScale;
  29139. var originalExtent = originalScale.getExtent();
  29140. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  29141. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  29142. return extent;
  29143. },
  29144. /**
  29145. * @param {Array.<number>} extent
  29146. */
  29147. unionExtent: function (extent) {
  29148. this._originalScale.unionExtent(extent);
  29149. var base = this.base;
  29150. extent[0] = mathLog(extent[0]) / mathLog(base);
  29151. extent[1] = mathLog(extent[1]) / mathLog(base);
  29152. scaleProto$1.unionExtent.call(this, extent);
  29153. },
  29154. /**
  29155. * @override
  29156. */
  29157. unionExtentFromData: function (data, dim) {
  29158. // TODO
  29159. // filter value that <= 0
  29160. this.unionExtent(data.getApproximateExtent(dim));
  29161. },
  29162. /**
  29163. * Update interval and extent of intervals for nice ticks
  29164. * @param {number} [approxTickNum = 10] Given approx tick number
  29165. */
  29166. niceTicks: function (approxTickNum) {
  29167. approxTickNum = approxTickNum || 10;
  29168. var extent = this._extent;
  29169. var span = extent[1] - extent[0];
  29170. if (span === Infinity || span <= 0) {
  29171. return;
  29172. }
  29173. var interval = quantity(span);
  29174. var err = approxTickNum / span * interval;
  29175. // Filter ticks to get closer to the desired count.
  29176. if (err <= 0.5) {
  29177. interval *= 10;
  29178. }
  29179. // Interval should be integer
  29180. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  29181. interval *= 10;
  29182. }
  29183. var niceExtent = [
  29184. round$2(mathCeil$1(extent[0] / interval) * interval),
  29185. round$2(mathFloor$1(extent[1] / interval) * interval)
  29186. ];
  29187. this._interval = interval;
  29188. this._niceExtent = niceExtent;
  29189. },
  29190. /**
  29191. * Nice extent.
  29192. * @override
  29193. */
  29194. niceExtent: function (opt) {
  29195. intervalScaleProto$1.niceExtent.call(this, opt);
  29196. var originalScale = this._originalScale;
  29197. originalScale.__fixMin = opt.fixMin;
  29198. originalScale.__fixMax = opt.fixMax;
  29199. }
  29200. });
  29201. each$1(['contain', 'normalize'], function (methodName) {
  29202. LogScale.prototype[methodName] = function (val) {
  29203. val = mathLog(val) / mathLog(this.base);
  29204. return scaleProto$1[methodName].call(this, val);
  29205. };
  29206. });
  29207. LogScale.create = function () {
  29208. return new LogScale();
  29209. };
  29210. function fixRoundingError(val, originalVal) {
  29211. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  29212. }
  29213. /*
  29214. * Licensed to the Apache Software Foundation (ASF) under one
  29215. * or more contributor license agreements. See the NOTICE file
  29216. * distributed with this work for additional information
  29217. * regarding copyright ownership. The ASF licenses this file
  29218. * to you under the Apache License, Version 2.0 (the
  29219. * "License"); you may not use this file except in compliance
  29220. * with the License. You may obtain a copy of the License at
  29221. *
  29222. * http://www.apache.org/licenses/LICENSE-2.0
  29223. *
  29224. * Unless required by applicable law or agreed to in writing,
  29225. * software distributed under the License is distributed on an
  29226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29227. * KIND, either express or implied. See the License for the
  29228. * specific language governing permissions and limitations
  29229. * under the License.
  29230. */
  29231. /**
  29232. * Get axis scale extent before niced.
  29233. * Item of returned array can only be number (including Infinity and NaN).
  29234. */
  29235. function getScaleExtent(scale, model) {
  29236. var scaleType = scale.type;
  29237. var min = model.getMin();
  29238. var max = model.getMax();
  29239. var fixMin = min != null;
  29240. var fixMax = max != null;
  29241. var originalExtent = scale.getExtent();
  29242. var axisDataLen;
  29243. var boundaryGap;
  29244. var span;
  29245. if (scaleType === 'ordinal') {
  29246. axisDataLen = model.getCategories().length;
  29247. }
  29248. else {
  29249. boundaryGap = model.get('boundaryGap');
  29250. if (!isArray(boundaryGap)) {
  29251. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  29252. }
  29253. if (typeof boundaryGap[0] === 'boolean') {
  29254. if (__DEV__) {
  29255. console.warn('Boolean type for boundaryGap is only '
  29256. + 'allowed for ordinal axis. Please use string in '
  29257. + 'percentage instead, e.g., "20%". Currently, '
  29258. + 'boundaryGap is set to be 0.');
  29259. }
  29260. boundaryGap = [0, 0];
  29261. }
  29262. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  29263. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  29264. span = (originalExtent[1] - originalExtent[0])
  29265. || Math.abs(originalExtent[0]);
  29266. }
  29267. // Notice: When min/max is not set (that is, when there are null/undefined,
  29268. // which is the most common case), these cases should be ensured:
  29269. // (1) For 'ordinal', show all axis.data.
  29270. // (2) For others:
  29271. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  29272. // disabled).
  29273. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  29274. // be the result that originalExtent enlarged by boundaryGap.
  29275. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  29276. // FIXME
  29277. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  29278. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  29279. // that the results processed by boundaryGap are positive/negative?
  29280. if (min == null) {
  29281. min = scaleType === 'ordinal'
  29282. ? (axisDataLen ? 0 : NaN)
  29283. : originalExtent[0] - boundaryGap[0] * span;
  29284. }
  29285. if (max == null) {
  29286. max = scaleType === 'ordinal'
  29287. ? (axisDataLen ? axisDataLen - 1 : NaN)
  29288. : originalExtent[1] + boundaryGap[1] * span;
  29289. }
  29290. if (min === 'dataMin') {
  29291. min = originalExtent[0];
  29292. }
  29293. else if (typeof min === 'function') {
  29294. min = min({
  29295. min: originalExtent[0],
  29296. max: originalExtent[1]
  29297. });
  29298. }
  29299. if (max === 'dataMax') {
  29300. max = originalExtent[1];
  29301. }
  29302. else if (typeof max === 'function') {
  29303. max = max({
  29304. min: originalExtent[0],
  29305. max: originalExtent[1]
  29306. });
  29307. }
  29308. (min == null || !isFinite(min)) && (min = NaN);
  29309. (max == null || !isFinite(max)) && (max = NaN);
  29310. scale.setBlank(
  29311. eqNaN(min)
  29312. || eqNaN(max)
  29313. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  29314. );
  29315. // Evaluate if axis needs cross zero
  29316. if (model.getNeedCrossZero()) {
  29317. // Axis is over zero and min is not set
  29318. if (min > 0 && max > 0 && !fixMin) {
  29319. min = 0;
  29320. }
  29321. // Axis is under zero and max is not set
  29322. if (min < 0 && max < 0 && !fixMax) {
  29323. max = 0;
  29324. }
  29325. }
  29326. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  29327. // is base axis
  29328. // FIXME
  29329. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  29330. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  29331. // Should not depend on series type `bar`?
  29332. // (3) Fix that might overlap when using dataZoom.
  29333. // (4) Consider other chart types using `barGrid`?
  29334. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  29335. var ecModel = model.ecModel;
  29336. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  29337. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  29338. var isBaseAxisAndHasBarSeries;
  29339. each$1(barSeriesModels, function (seriesModel) {
  29340. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  29341. });
  29342. if (isBaseAxisAndHasBarSeries) {
  29343. // Calculate placement of bars on axis
  29344. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  29345. // Adjust axis min and max to account for overflow
  29346. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  29347. min = adjustedScale.min;
  29348. max = adjustedScale.max;
  29349. }
  29350. }
  29351. return [min, max];
  29352. }
  29353. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  29354. // Get Axis Length
  29355. var axisExtent = model.axis.getExtent();
  29356. var axisLength = axisExtent[1] - axisExtent[0];
  29357. // Get bars on current base axis and calculate min and max overflow
  29358. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  29359. if (barsOnCurrentAxis === undefined) {
  29360. return {min: min, max: max};
  29361. }
  29362. var minOverflow = Infinity;
  29363. each$1(barsOnCurrentAxis, function (item) {
  29364. minOverflow = Math.min(item.offset, minOverflow);
  29365. });
  29366. var maxOverflow = -Infinity;
  29367. each$1(barsOnCurrentAxis, function (item) {
  29368. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  29369. });
  29370. minOverflow = Math.abs(minOverflow);
  29371. maxOverflow = Math.abs(maxOverflow);
  29372. var totalOverFlow = minOverflow + maxOverflow;
  29373. // Calulate required buffer based on old range and overflow
  29374. var oldRange = max - min;
  29375. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  29376. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  29377. max += overflowBuffer * (maxOverflow / totalOverFlow);
  29378. min -= overflowBuffer * (minOverflow / totalOverFlow);
  29379. return {min: min, max: max};
  29380. }
  29381. function niceScaleExtent(scale, model) {
  29382. var extent = getScaleExtent(scale, model);
  29383. var fixMin = model.getMin() != null;
  29384. var fixMax = model.getMax() != null;
  29385. var splitNumber = model.get('splitNumber');
  29386. if (scale.type === 'log') {
  29387. scale.base = model.get('logBase');
  29388. }
  29389. var scaleType = scale.type;
  29390. scale.setExtent(extent[0], extent[1]);
  29391. scale.niceExtent({
  29392. splitNumber: splitNumber,
  29393. fixMin: fixMin,
  29394. fixMax: fixMax,
  29395. minInterval: (scaleType === 'interval' || scaleType === 'time')
  29396. ? model.get('minInterval') : null,
  29397. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  29398. ? model.get('maxInterval') : null
  29399. });
  29400. // If some one specified the min, max. And the default calculated interval
  29401. // is not good enough. He can specify the interval. It is often appeared
  29402. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  29403. // to be 60.
  29404. // FIXME
  29405. var interval = model.get('interval');
  29406. if (interval != null) {
  29407. scale.setInterval && scale.setInterval(interval);
  29408. }
  29409. }
  29410. /**
  29411. * @param {module:echarts/model/Model} model
  29412. * @param {string} [axisType] Default retrieve from model.type
  29413. * @return {module:echarts/scale/*}
  29414. */
  29415. function createScaleByModel(model, axisType) {
  29416. axisType = axisType || model.get('type');
  29417. if (axisType) {
  29418. switch (axisType) {
  29419. // Buildin scale
  29420. case 'category':
  29421. return new OrdinalScale(
  29422. model.getOrdinalMeta
  29423. ? model.getOrdinalMeta()
  29424. : model.getCategories(),
  29425. [Infinity, -Infinity]
  29426. );
  29427. case 'value':
  29428. return new IntervalScale();
  29429. // Extended scale, like time and log
  29430. default:
  29431. return (Scale.getClass(axisType) || IntervalScale).create(model);
  29432. }
  29433. }
  29434. }
  29435. /**
  29436. * Check if the axis corss 0
  29437. */
  29438. function ifAxisCrossZero(axis) {
  29439. var dataExtent = axis.scale.getExtent();
  29440. var min = dataExtent[0];
  29441. var max = dataExtent[1];
  29442. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  29443. }
  29444. /**
  29445. * @param {module:echarts/coord/Axis} axis
  29446. * @return {Function} Label formatter function.
  29447. * param: {number} tickValue,
  29448. * param: {number} idx, the index in all ticks.
  29449. * If category axis, this param is not requied.
  29450. * return: {string} label string.
  29451. */
  29452. function makeLabelFormatter(axis) {
  29453. var labelFormatter = axis.getLabelModel().get('formatter');
  29454. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  29455. if (typeof labelFormatter === 'string') {
  29456. labelFormatter = (function (tpl) {
  29457. return function (val) {
  29458. // For category axis, get raw value; for numeric axis,
  29459. // get foramtted label like '1,333,444'.
  29460. val = axis.scale.getLabel(val);
  29461. return tpl.replace('{value}', val != null ? val : '');
  29462. };
  29463. })(labelFormatter);
  29464. // Consider empty array
  29465. return labelFormatter;
  29466. }
  29467. else if (typeof labelFormatter === 'function') {
  29468. return function (tickValue, idx) {
  29469. // The original intention of `idx` is "the index of the tick in all ticks".
  29470. // But the previous implementation of category axis do not consider the
  29471. // `axisLabel.interval`, which cause that, for example, the `interval` is
  29472. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  29473. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  29474. // the definition here for back compatibility.
  29475. if (categoryTickStart != null) {
  29476. idx = tickValue - categoryTickStart;
  29477. }
  29478. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  29479. };
  29480. }
  29481. else {
  29482. return function (tick) {
  29483. return axis.scale.getLabel(tick);
  29484. };
  29485. }
  29486. }
  29487. function getAxisRawValue(axis, value) {
  29488. // In category axis with data zoom, tick is not the original
  29489. // index of axis.data. So tick should not be exposed to user
  29490. // in category axis.
  29491. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  29492. }
  29493. /**
  29494. * @param {module:echarts/coord/Axis} axis
  29495. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  29496. */
  29497. function estimateLabelUnionRect(axis) {
  29498. var axisModel = axis.model;
  29499. var scale = axis.scale;
  29500. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  29501. return;
  29502. }
  29503. var isCategory = axis.type === 'category';
  29504. var realNumberScaleTicks;
  29505. var tickCount;
  29506. var categoryScaleExtent = scale.getExtent();
  29507. // Optimize for large category data, avoid call `getTicks()`.
  29508. if (isCategory) {
  29509. tickCount = scale.count();
  29510. }
  29511. else {
  29512. realNumberScaleTicks = scale.getTicks();
  29513. tickCount = realNumberScaleTicks.length;
  29514. }
  29515. var axisLabelModel = axis.getLabelModel();
  29516. var labelFormatter = makeLabelFormatter(axis);
  29517. var rect;
  29518. var step = 1;
  29519. // Simple optimization for large amount of labels
  29520. if (tickCount > 40) {
  29521. step = Math.ceil(tickCount / 40);
  29522. }
  29523. for (var i = 0; i < tickCount; i += step) {
  29524. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  29525. var label = labelFormatter(tickValue);
  29526. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  29527. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  29528. rect ? rect.union(singleRect) : (rect = singleRect);
  29529. }
  29530. return rect;
  29531. }
  29532. function rotateTextRect(textRect, rotate) {
  29533. var rotateRadians = rotate * Math.PI / 180;
  29534. var boundingBox = textRect.plain();
  29535. var beforeWidth = boundingBox.width;
  29536. var beforeHeight = boundingBox.height;
  29537. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  29538. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  29539. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  29540. return rotatedRect;
  29541. }
  29542. /**
  29543. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  29544. * @return {number|String} Can be null|'auto'|number|function
  29545. */
  29546. function getOptionCategoryInterval(model) {
  29547. var interval = model.get('interval');
  29548. return interval == null ? 'auto' : interval;
  29549. }
  29550. /**
  29551. * Set `categoryInterval` as 0 implicitly indicates that
  29552. * show all labels reguardless of overlap.
  29553. * @param {Object} axis axisModel.axis
  29554. * @return {boolean}
  29555. */
  29556. function shouldShowAllLabels(axis) {
  29557. return axis.type === 'category'
  29558. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  29559. }
  29560. /*
  29561. * Licensed to the Apache Software Foundation (ASF) under one
  29562. * or more contributor license agreements. See the NOTICE file
  29563. * distributed with this work for additional information
  29564. * regarding copyright ownership. The ASF licenses this file
  29565. * to you under the Apache License, Version 2.0 (the
  29566. * "License"); you may not use this file except in compliance
  29567. * with the License. You may obtain a copy of the License at
  29568. *
  29569. * http://www.apache.org/licenses/LICENSE-2.0
  29570. *
  29571. * Unless required by applicable law or agreed to in writing,
  29572. * software distributed under the License is distributed on an
  29573. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29574. * KIND, either express or implied. See the License for the
  29575. * specific language governing permissions and limitations
  29576. * under the License.
  29577. */
  29578. // import * as axisHelper from './axisHelper';
  29579. var axisModelCommonMixin = {
  29580. /**
  29581. * @param {boolean} origin
  29582. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  29583. */
  29584. getMin: function (origin) {
  29585. var option = this.option;
  29586. var min = (!origin && option.rangeStart != null)
  29587. ? option.rangeStart : option.min;
  29588. if (this.axis
  29589. && min != null
  29590. && min !== 'dataMin'
  29591. && typeof min !== 'function'
  29592. && !eqNaN(min)
  29593. ) {
  29594. min = this.axis.scale.parse(min);
  29595. }
  29596. return min;
  29597. },
  29598. /**
  29599. * @param {boolean} origin
  29600. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  29601. */
  29602. getMax: function (origin) {
  29603. var option = this.option;
  29604. var max = (!origin && option.rangeEnd != null)
  29605. ? option.rangeEnd : option.max;
  29606. if (this.axis
  29607. && max != null
  29608. && max !== 'dataMax'
  29609. && typeof max !== 'function'
  29610. && !eqNaN(max)
  29611. ) {
  29612. max = this.axis.scale.parse(max);
  29613. }
  29614. return max;
  29615. },
  29616. /**
  29617. * @return {boolean}
  29618. */
  29619. getNeedCrossZero: function () {
  29620. var option = this.option;
  29621. return (option.rangeStart != null || option.rangeEnd != null)
  29622. ? false : !option.scale;
  29623. },
  29624. /**
  29625. * Should be implemented by each axis model if necessary.
  29626. * @return {module:echarts/model/Component} coordinate system model
  29627. */
  29628. getCoordSysModel: noop,
  29629. /**
  29630. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  29631. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  29632. */
  29633. setRange: function (rangeStart, rangeEnd) {
  29634. this.option.rangeStart = rangeStart;
  29635. this.option.rangeEnd = rangeEnd;
  29636. },
  29637. /**
  29638. * Reset range
  29639. */
  29640. resetRange: function () {
  29641. // rangeStart and rangeEnd is readonly.
  29642. this.option.rangeStart = this.option.rangeEnd = null;
  29643. }
  29644. };
  29645. /*
  29646. * Licensed to the Apache Software Foundation (ASF) under one
  29647. * or more contributor license agreements. See the NOTICE file
  29648. * distributed with this work for additional information
  29649. * regarding copyright ownership. The ASF licenses this file
  29650. * to you under the Apache License, Version 2.0 (the
  29651. * "License"); you may not use this file except in compliance
  29652. * with the License. You may obtain a copy of the License at
  29653. *
  29654. * http://www.apache.org/licenses/LICENSE-2.0
  29655. *
  29656. * Unless required by applicable law or agreed to in writing,
  29657. * software distributed under the License is distributed on an
  29658. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29659. * KIND, either express or implied. See the License for the
  29660. * specific language governing permissions and limitations
  29661. * under the License.
  29662. */
  29663. // Symbol factory
  29664. /**
  29665. * Triangle shape
  29666. * @inner
  29667. */
  29668. var Triangle = extendShape({
  29669. type: 'triangle',
  29670. shape: {
  29671. cx: 0,
  29672. cy: 0,
  29673. width: 0,
  29674. height: 0
  29675. },
  29676. buildPath: function (path, shape) {
  29677. var cx = shape.cx;
  29678. var cy = shape.cy;
  29679. var width = shape.width / 2;
  29680. var height = shape.height / 2;
  29681. path.moveTo(cx, cy - height);
  29682. path.lineTo(cx + width, cy + height);
  29683. path.lineTo(cx - width, cy + height);
  29684. path.closePath();
  29685. }
  29686. });
  29687. /**
  29688. * Diamond shape
  29689. * @inner
  29690. */
  29691. var Diamond = extendShape({
  29692. type: 'diamond',
  29693. shape: {
  29694. cx: 0,
  29695. cy: 0,
  29696. width: 0,
  29697. height: 0
  29698. },
  29699. buildPath: function (path, shape) {
  29700. var cx = shape.cx;
  29701. var cy = shape.cy;
  29702. var width = shape.width / 2;
  29703. var height = shape.height / 2;
  29704. path.moveTo(cx, cy - height);
  29705. path.lineTo(cx + width, cy);
  29706. path.lineTo(cx, cy + height);
  29707. path.lineTo(cx - width, cy);
  29708. path.closePath();
  29709. }
  29710. });
  29711. /**
  29712. * Pin shape
  29713. * @inner
  29714. */
  29715. var Pin = extendShape({
  29716. type: 'pin',
  29717. shape: {
  29718. // x, y on the cusp
  29719. x: 0,
  29720. y: 0,
  29721. width: 0,
  29722. height: 0
  29723. },
  29724. buildPath: function (path, shape) {
  29725. var x = shape.x;
  29726. var y = shape.y;
  29727. var w = shape.width / 5 * 3;
  29728. // Height must be larger than width
  29729. var h = Math.max(w, shape.height);
  29730. var r = w / 2;
  29731. // Dist on y with tangent point and circle center
  29732. var dy = r * r / (h - r);
  29733. var cy = y - h + r + dy;
  29734. var angle = Math.asin(dy / r);
  29735. // Dist on x with tangent point and circle center
  29736. var dx = Math.cos(angle) * r;
  29737. var tanX = Math.sin(angle);
  29738. var tanY = Math.cos(angle);
  29739. var cpLen = r * 0.6;
  29740. var cpLen2 = r * 0.7;
  29741. path.moveTo(x - dx, cy + dy);
  29742. path.arc(
  29743. x, cy, r,
  29744. Math.PI - angle,
  29745. Math.PI * 2 + angle
  29746. );
  29747. path.bezierCurveTo(
  29748. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  29749. x, y - cpLen2,
  29750. x, y
  29751. );
  29752. path.bezierCurveTo(
  29753. x, y - cpLen2,
  29754. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  29755. x - dx, cy + dy
  29756. );
  29757. path.closePath();
  29758. }
  29759. });
  29760. /**
  29761. * Arrow shape
  29762. * @inner
  29763. */
  29764. var Arrow = extendShape({
  29765. type: 'arrow',
  29766. shape: {
  29767. x: 0,
  29768. y: 0,
  29769. width: 0,
  29770. height: 0
  29771. },
  29772. buildPath: function (ctx, shape) {
  29773. var height = shape.height;
  29774. var width = shape.width;
  29775. var x = shape.x;
  29776. var y = shape.y;
  29777. var dx = width / 3 * 2;
  29778. ctx.moveTo(x, y);
  29779. ctx.lineTo(x + dx, y + height);
  29780. ctx.lineTo(x, y + height / 4 * 3);
  29781. ctx.lineTo(x - dx, y + height);
  29782. ctx.lineTo(x, y);
  29783. ctx.closePath();
  29784. }
  29785. });
  29786. /**
  29787. * Map of path contructors
  29788. * @type {Object.<string, module:zrender/graphic/Path>}
  29789. */
  29790. var symbolCtors = {
  29791. line: Line,
  29792. rect: Rect,
  29793. roundRect: Rect,
  29794. square: Rect,
  29795. circle: Circle,
  29796. diamond: Diamond,
  29797. pin: Pin,
  29798. arrow: Arrow,
  29799. triangle: Triangle
  29800. };
  29801. var symbolShapeMakers = {
  29802. line: function (x, y, w, h, shape) {
  29803. // FIXME
  29804. shape.x1 = x;
  29805. shape.y1 = y + h / 2;
  29806. shape.x2 = x + w;
  29807. shape.y2 = y + h / 2;
  29808. },
  29809. rect: function (x, y, w, h, shape) {
  29810. shape.x = x;
  29811. shape.y = y;
  29812. shape.width = w;
  29813. shape.height = h;
  29814. },
  29815. roundRect: function (x, y, w, h, shape) {
  29816. shape.x = x;
  29817. shape.y = y;
  29818. shape.width = w;
  29819. shape.height = h;
  29820. shape.r = Math.min(w, h) / 4;
  29821. },
  29822. square: function (x, y, w, h, shape) {
  29823. var size = Math.min(w, h);
  29824. shape.x = x;
  29825. shape.y = y;
  29826. shape.width = size;
  29827. shape.height = size;
  29828. },
  29829. circle: function (x, y, w, h, shape) {
  29830. // Put circle in the center of square
  29831. shape.cx = x + w / 2;
  29832. shape.cy = y + h / 2;
  29833. shape.r = Math.min(w, h) / 2;
  29834. },
  29835. diamond: function (x, y, w, h, shape) {
  29836. shape.cx = x + w / 2;
  29837. shape.cy = y + h / 2;
  29838. shape.width = w;
  29839. shape.height = h;
  29840. },
  29841. pin: function (x, y, w, h, shape) {
  29842. shape.x = x + w / 2;
  29843. shape.y = y + h / 2;
  29844. shape.width = w;
  29845. shape.height = h;
  29846. },
  29847. arrow: function (x, y, w, h, shape) {
  29848. shape.x = x + w / 2;
  29849. shape.y = y + h / 2;
  29850. shape.width = w;
  29851. shape.height = h;
  29852. },
  29853. triangle: function (x, y, w, h, shape) {
  29854. shape.cx = x + w / 2;
  29855. shape.cy = y + h / 2;
  29856. shape.width = w;
  29857. shape.height = h;
  29858. }
  29859. };
  29860. var symbolBuildProxies = {};
  29861. each$1(symbolCtors, function (Ctor, name) {
  29862. symbolBuildProxies[name] = new Ctor();
  29863. });
  29864. var SymbolClz = extendShape({
  29865. type: 'symbol',
  29866. shape: {
  29867. symbolType: '',
  29868. x: 0,
  29869. y: 0,
  29870. width: 0,
  29871. height: 0
  29872. },
  29873. beforeBrush: function () {
  29874. var style = this.style;
  29875. var shape = this.shape;
  29876. // FIXME
  29877. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  29878. style.textPosition = ['50%', '40%'];
  29879. style.textAlign = 'center';
  29880. style.textVerticalAlign = 'middle';
  29881. }
  29882. },
  29883. buildPath: function (ctx, shape, inBundle) {
  29884. var symbolType = shape.symbolType;
  29885. var proxySymbol = symbolBuildProxies[symbolType];
  29886. if (shape.symbolType !== 'none') {
  29887. if (!proxySymbol) {
  29888. // Default rect
  29889. symbolType = 'rect';
  29890. proxySymbol = symbolBuildProxies[symbolType];
  29891. }
  29892. symbolShapeMakers[symbolType](
  29893. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  29894. );
  29895. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  29896. }
  29897. }
  29898. });
  29899. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  29900. function symbolPathSetColor(color, innerColor) {
  29901. if (this.type !== 'image') {
  29902. var symbolStyle = this.style;
  29903. var symbolShape = this.shape;
  29904. if (symbolShape && symbolShape.symbolType === 'line') {
  29905. symbolStyle.stroke = color;
  29906. }
  29907. else if (this.__isEmptyBrush) {
  29908. symbolStyle.stroke = color;
  29909. symbolStyle.fill = innerColor || '#fff';
  29910. }
  29911. else {
  29912. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  29913. symbolStyle.fill && (symbolStyle.fill = color);
  29914. symbolStyle.stroke && (symbolStyle.stroke = color);
  29915. }
  29916. this.dirty(false);
  29917. }
  29918. }
  29919. /**
  29920. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  29921. * @param {string} symbolType
  29922. * @param {number} x
  29923. * @param {number} y
  29924. * @param {number} w
  29925. * @param {number} h
  29926. * @param {string} color
  29927. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  29928. * for path and image only.
  29929. */
  29930. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  29931. // TODO Support image object, DynamicImage.
  29932. var isEmpty = symbolType.indexOf('empty') === 0;
  29933. if (isEmpty) {
  29934. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  29935. }
  29936. var symbolPath;
  29937. if (symbolType.indexOf('image://') === 0) {
  29938. symbolPath = makeImage(
  29939. symbolType.slice(8),
  29940. new BoundingRect(x, y, w, h),
  29941. keepAspect ? 'center' : 'cover'
  29942. );
  29943. }
  29944. else if (symbolType.indexOf('path://') === 0) {
  29945. symbolPath = makePath(
  29946. symbolType.slice(7),
  29947. {},
  29948. new BoundingRect(x, y, w, h),
  29949. keepAspect ? 'center' : 'cover'
  29950. );
  29951. }
  29952. else {
  29953. symbolPath = new SymbolClz({
  29954. shape: {
  29955. symbolType: symbolType,
  29956. x: x,
  29957. y: y,
  29958. width: w,
  29959. height: h
  29960. }
  29961. });
  29962. }
  29963. symbolPath.__isEmptyBrush = isEmpty;
  29964. symbolPath.setColor = symbolPathSetColor;
  29965. symbolPath.setColor(color);
  29966. return symbolPath;
  29967. }
  29968. /*
  29969. * Licensed to the Apache Software Foundation (ASF) under one
  29970. * or more contributor license agreements. See the NOTICE file
  29971. * distributed with this work for additional information
  29972. * regarding copyright ownership. The ASF licenses this file
  29973. * to you under the Apache License, Version 2.0 (the
  29974. * "License"); you may not use this file except in compliance
  29975. * with the License. You may obtain a copy of the License at
  29976. *
  29977. * http://www.apache.org/licenses/LICENSE-2.0
  29978. *
  29979. * Unless required by applicable law or agreed to in writing,
  29980. * software distributed under the License is distributed on an
  29981. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29982. * KIND, either express or implied. See the License for the
  29983. * specific language governing permissions and limitations
  29984. * under the License.
  29985. */
  29986. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  29987. /**
  29988. * Create a muti dimension List structure from seriesModel.
  29989. * @param {module:echarts/model/Model} seriesModel
  29990. * @return {module:echarts/data/List} list
  29991. */
  29992. function createList(seriesModel) {
  29993. return createListFromArray(seriesModel.getSource(), seriesModel);
  29994. }
  29995. var dataStack$1 = {
  29996. isDimensionStacked: isDimensionStacked,
  29997. enableDataStack: enableDataStack,
  29998. getStackedDimension: getStackedDimension
  29999. };
  30000. /**
  30001. * Create scale
  30002. * @param {Array.<number>} dataExtent
  30003. * @param {Object|module:echarts/Model} option
  30004. */
  30005. function createScale(dataExtent, option) {
  30006. var axisModel = option;
  30007. if (!Model.isInstance(option)) {
  30008. axisModel = new Model(option);
  30009. mixin(axisModel, axisModelCommonMixin);
  30010. }
  30011. var scale = createScaleByModel(axisModel);
  30012. scale.setExtent(dataExtent[0], dataExtent[1]);
  30013. niceScaleExtent(scale, axisModel);
  30014. return scale;
  30015. }
  30016. /**
  30017. * Mixin common methods to axis model,
  30018. *
  30019. * Inlcude methods
  30020. * `getFormattedLabels() => Array.<string>`
  30021. * `getCategories() => Array.<string>`
  30022. * `getMin(origin: boolean) => number`
  30023. * `getMax(origin: boolean) => number`
  30024. * `getNeedCrossZero() => boolean`
  30025. * `setRange(start: number, end: number)`
  30026. * `resetRange()`
  30027. */
  30028. function mixinAxisModelCommonMethods(Model$$1) {
  30029. mixin(Model$$1, axisModelCommonMixin);
  30030. }
  30031. var helper = (Object.freeze || Object)({
  30032. createList: createList,
  30033. getLayoutRect: getLayoutRect,
  30034. dataStack: dataStack$1,
  30035. createScale: createScale,
  30036. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  30037. completeDimensions: completeDimensions,
  30038. createDimensions: createDimensions,
  30039. createSymbol: createSymbol
  30040. });
  30041. var EPSILON$3 = 1e-8;
  30042. function isAroundEqual$1(a, b) {
  30043. return Math.abs(a - b) < EPSILON$3;
  30044. }
  30045. function contain$1(points, x, y) {
  30046. var w = 0;
  30047. var p = points[0];
  30048. if (!p) {
  30049. return false;
  30050. }
  30051. for (var i = 1; i < points.length; i++) {
  30052. var p2 = points[i];
  30053. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  30054. p = p2;
  30055. }
  30056. // Close polygon
  30057. var p0 = points[0];
  30058. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  30059. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  30060. }
  30061. return w !== 0;
  30062. }
  30063. /*
  30064. * Licensed to the Apache Software Foundation (ASF) under one
  30065. * or more contributor license agreements. See the NOTICE file
  30066. * distributed with this work for additional information
  30067. * regarding copyright ownership. The ASF licenses this file
  30068. * to you under the Apache License, Version 2.0 (the
  30069. * "License"); you may not use this file except in compliance
  30070. * with the License. You may obtain a copy of the License at
  30071. *
  30072. * http://www.apache.org/licenses/LICENSE-2.0
  30073. *
  30074. * Unless required by applicable law or agreed to in writing,
  30075. * software distributed under the License is distributed on an
  30076. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30077. * KIND, either express or implied. See the License for the
  30078. * specific language governing permissions and limitations
  30079. * under the License.
  30080. */
  30081. /**
  30082. * @module echarts/coord/geo/Region
  30083. */
  30084. /**
  30085. * @param {string|Region} name
  30086. * @param {Array} geometries
  30087. * @param {Array.<number>} cp
  30088. */
  30089. function Region(name, geometries, cp) {
  30090. /**
  30091. * @type {string}
  30092. * @readOnly
  30093. */
  30094. this.name = name;
  30095. /**
  30096. * @type {Array.<Array>}
  30097. * @readOnly
  30098. */
  30099. this.geometries = geometries;
  30100. if (!cp) {
  30101. var rect = this.getBoundingRect();
  30102. cp = [
  30103. rect.x + rect.width / 2,
  30104. rect.y + rect.height / 2
  30105. ];
  30106. }
  30107. else {
  30108. cp = [cp[0], cp[1]];
  30109. }
  30110. /**
  30111. * @type {Array.<number>}
  30112. */
  30113. this.center = cp;
  30114. }
  30115. Region.prototype = {
  30116. constructor: Region,
  30117. properties: null,
  30118. /**
  30119. * @return {module:zrender/core/BoundingRect}
  30120. */
  30121. getBoundingRect: function () {
  30122. var rect = this._rect;
  30123. if (rect) {
  30124. return rect;
  30125. }
  30126. var MAX_NUMBER = Number.MAX_VALUE;
  30127. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  30128. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  30129. var min2 = [];
  30130. var max2 = [];
  30131. var geometries = this.geometries;
  30132. for (var i = 0; i < geometries.length; i++) {
  30133. // Only support polygon
  30134. if (geometries[i].type !== 'polygon') {
  30135. continue;
  30136. }
  30137. // Doesn't consider hole
  30138. var exterior = geometries[i].exterior;
  30139. fromPoints(exterior, min2, max2);
  30140. min(min$$1, min$$1, min2);
  30141. max(max$$1, max$$1, max2);
  30142. }
  30143. // No data
  30144. if (i === 0) {
  30145. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  30146. }
  30147. return (this._rect = new BoundingRect(
  30148. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  30149. ));
  30150. },
  30151. /**
  30152. * @param {<Array.<number>} coord
  30153. * @return {boolean}
  30154. */
  30155. contain: function (coord) {
  30156. var rect = this.getBoundingRect();
  30157. var geometries = this.geometries;
  30158. if (!rect.contain(coord[0], coord[1])) {
  30159. return false;
  30160. }
  30161. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  30162. // Only support polygon.
  30163. if (geometries[i].type !== 'polygon') {
  30164. continue;
  30165. }
  30166. var exterior = geometries[i].exterior;
  30167. var interiors = geometries[i].interiors;
  30168. if (contain$1(exterior, coord[0], coord[1])) {
  30169. // Not in the region if point is in the hole.
  30170. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  30171. if (contain$1(interiors[k])) {
  30172. continue loopGeo;
  30173. }
  30174. }
  30175. return true;
  30176. }
  30177. }
  30178. return false;
  30179. },
  30180. transformTo: function (x, y, width, height) {
  30181. var rect = this.getBoundingRect();
  30182. var aspect = rect.width / rect.height;
  30183. if (!width) {
  30184. width = aspect * height;
  30185. }
  30186. else if (!height) {
  30187. height = width / aspect;
  30188. }
  30189. var target = new BoundingRect(x, y, width, height);
  30190. var transform = rect.calculateTransform(target);
  30191. var geometries = this.geometries;
  30192. for (var i = 0; i < geometries.length; i++) {
  30193. // Only support polygon.
  30194. if (geometries[i].type !== 'polygon') {
  30195. continue;
  30196. }
  30197. var exterior = geometries[i].exterior;
  30198. var interiors = geometries[i].interiors;
  30199. for (var p = 0; p < exterior.length; p++) {
  30200. applyTransform(exterior[p], exterior[p], transform);
  30201. }
  30202. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  30203. for (var p = 0; p < interiors[h].length; p++) {
  30204. applyTransform(interiors[h][p], interiors[h][p], transform);
  30205. }
  30206. }
  30207. }
  30208. rect = this._rect;
  30209. rect.copy(target);
  30210. // Update center
  30211. this.center = [
  30212. rect.x + rect.width / 2,
  30213. rect.y + rect.height / 2
  30214. ];
  30215. },
  30216. cloneShallow: function (name) {
  30217. name == null && (name = this.name);
  30218. var newRegion = new Region(name, this.geometries, this.center);
  30219. newRegion._rect = this._rect;
  30220. newRegion.transformTo = null; // Simply avoid to be called.
  30221. return newRegion;
  30222. }
  30223. };
  30224. /*
  30225. * Licensed to the Apache Software Foundation (ASF) under one
  30226. * or more contributor license agreements. See the NOTICE file
  30227. * distributed with this work for additional information
  30228. * regarding copyright ownership. The ASF licenses this file
  30229. * to you under the Apache License, Version 2.0 (the
  30230. * "License"); you may not use this file except in compliance
  30231. * with the License. You may obtain a copy of the License at
  30232. *
  30233. * http://www.apache.org/licenses/LICENSE-2.0
  30234. *
  30235. * Unless required by applicable law or agreed to in writing,
  30236. * software distributed under the License is distributed on an
  30237. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30238. * KIND, either express or implied. See the License for the
  30239. * specific language governing permissions and limitations
  30240. * under the License.
  30241. */
  30242. /**
  30243. * Parse and decode geo json
  30244. * @module echarts/coord/geo/parseGeoJson
  30245. */
  30246. function decode(json) {
  30247. if (!json.UTF8Encoding) {
  30248. return json;
  30249. }
  30250. var encodeScale = json.UTF8Scale;
  30251. if (encodeScale == null) {
  30252. encodeScale = 1024;
  30253. }
  30254. var features = json.features;
  30255. for (var f = 0; f < features.length; f++) {
  30256. var feature = features[f];
  30257. var geometry = feature.geometry;
  30258. var coordinates = geometry.coordinates;
  30259. var encodeOffsets = geometry.encodeOffsets;
  30260. for (var c = 0; c < coordinates.length; c++) {
  30261. var coordinate = coordinates[c];
  30262. if (geometry.type === 'Polygon') {
  30263. coordinates[c] = decodePolygon(
  30264. coordinate,
  30265. encodeOffsets[c],
  30266. encodeScale
  30267. );
  30268. }
  30269. else if (geometry.type === 'MultiPolygon') {
  30270. for (var c2 = 0; c2 < coordinate.length; c2++) {
  30271. var polygon = coordinate[c2];
  30272. coordinate[c2] = decodePolygon(
  30273. polygon,
  30274. encodeOffsets[c][c2],
  30275. encodeScale
  30276. );
  30277. }
  30278. }
  30279. }
  30280. }
  30281. // Has been decoded
  30282. json.UTF8Encoding = false;
  30283. return json;
  30284. }
  30285. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  30286. var result = [];
  30287. var prevX = encodeOffsets[0];
  30288. var prevY = encodeOffsets[1];
  30289. for (var i = 0; i < coordinate.length; i += 2) {
  30290. var x = coordinate.charCodeAt(i) - 64;
  30291. var y = coordinate.charCodeAt(i + 1) - 64;
  30292. // ZigZag decoding
  30293. x = (x >> 1) ^ (-(x & 1));
  30294. y = (y >> 1) ^ (-(y & 1));
  30295. // Delta deocding
  30296. x += prevX;
  30297. y += prevY;
  30298. prevX = x;
  30299. prevY = y;
  30300. // Dequantize
  30301. result.push([x / encodeScale, y / encodeScale]);
  30302. }
  30303. return result;
  30304. }
  30305. /**
  30306. * @alias module:echarts/coord/geo/parseGeoJson
  30307. * @param {Object} geoJson
  30308. * @return {module:zrender/container/Group}
  30309. */
  30310. var parseGeoJson$1 = function (geoJson) {
  30311. decode(geoJson);
  30312. return map(filter(geoJson.features, function (featureObj) {
  30313. // Output of mapshaper may have geometry null
  30314. return featureObj.geometry
  30315. && featureObj.properties
  30316. && featureObj.geometry.coordinates.length > 0;
  30317. }), function (featureObj) {
  30318. var properties = featureObj.properties;
  30319. var geo = featureObj.geometry;
  30320. var coordinates = geo.coordinates;
  30321. var geometries = [];
  30322. if (geo.type === 'Polygon') {
  30323. geometries.push({
  30324. type: 'polygon',
  30325. // According to the GeoJSON specification.
  30326. // First must be exterior, and the rest are all interior(holes).
  30327. exterior: coordinates[0],
  30328. interiors: coordinates.slice(1)
  30329. });
  30330. }
  30331. if (geo.type === 'MultiPolygon') {
  30332. each$1(coordinates, function (item) {
  30333. if (item[0]) {
  30334. geometries.push({
  30335. type: 'polygon',
  30336. exterior: item[0],
  30337. interiors: item.slice(1)
  30338. });
  30339. }
  30340. });
  30341. }
  30342. var region = new Region(
  30343. properties.name,
  30344. geometries,
  30345. properties.cp
  30346. );
  30347. region.properties = properties;
  30348. return region;
  30349. });
  30350. };
  30351. /*
  30352. * Licensed to the Apache Software Foundation (ASF) under one
  30353. * or more contributor license agreements. See the NOTICE file
  30354. * distributed with this work for additional information
  30355. * regarding copyright ownership. The ASF licenses this file
  30356. * to you under the Apache License, Version 2.0 (the
  30357. * "License"); you may not use this file except in compliance
  30358. * with the License. You may obtain a copy of the License at
  30359. *
  30360. * http://www.apache.org/licenses/LICENSE-2.0
  30361. *
  30362. * Unless required by applicable law or agreed to in writing,
  30363. * software distributed under the License is distributed on an
  30364. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30365. * KIND, either express or implied. See the License for the
  30366. * specific language governing permissions and limitations
  30367. * under the License.
  30368. */
  30369. var inner$6 = makeInner();
  30370. /**
  30371. * @param {module:echats/coord/Axis} axis
  30372. * @return {Object} {
  30373. * labels: [{
  30374. * formattedLabel: string,
  30375. * rawLabel: string,
  30376. * tickValue: number
  30377. * }, ...],
  30378. * labelCategoryInterval: number
  30379. * }
  30380. */
  30381. function createAxisLabels(axis) {
  30382. // Only ordinal scale support tick interval
  30383. return axis.type === 'category'
  30384. ? makeCategoryLabels(axis)
  30385. : makeRealNumberLabels(axis);
  30386. }
  30387. /**
  30388. * @param {module:echats/coord/Axis} axis
  30389. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  30390. * @return {Object} {
  30391. * ticks: Array.<number>
  30392. * tickCategoryInterval: number
  30393. * }
  30394. */
  30395. function createAxisTicks(axis, tickModel) {
  30396. // Only ordinal scale support tick interval
  30397. return axis.type === 'category'
  30398. ? makeCategoryTicks(axis, tickModel)
  30399. : {ticks: axis.scale.getTicks()};
  30400. }
  30401. function makeCategoryLabels(axis) {
  30402. var labelModel = axis.getLabelModel();
  30403. var result = makeCategoryLabelsActually(axis, labelModel);
  30404. return (!labelModel.get('show') || axis.scale.isBlank())
  30405. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  30406. : result;
  30407. }
  30408. function makeCategoryLabelsActually(axis, labelModel) {
  30409. var labelsCache = getListCache(axis, 'labels');
  30410. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  30411. var result = listCacheGet(labelsCache, optionLabelInterval);
  30412. if (result) {
  30413. return result;
  30414. }
  30415. var labels;
  30416. var numericLabelInterval;
  30417. if (isFunction$1(optionLabelInterval)) {
  30418. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  30419. }
  30420. else {
  30421. numericLabelInterval = optionLabelInterval === 'auto'
  30422. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  30423. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  30424. }
  30425. // Cache to avoid calling interval function repeatly.
  30426. return listCacheSet(labelsCache, optionLabelInterval, {
  30427. labels: labels, labelCategoryInterval: numericLabelInterval
  30428. });
  30429. }
  30430. function makeCategoryTicks(axis, tickModel) {
  30431. var ticksCache = getListCache(axis, 'ticks');
  30432. var optionTickInterval = getOptionCategoryInterval(tickModel);
  30433. var result = listCacheGet(ticksCache, optionTickInterval);
  30434. if (result) {
  30435. return result;
  30436. }
  30437. var ticks;
  30438. var tickCategoryInterval;
  30439. // Optimize for the case that large category data and no label displayed,
  30440. // we should not return all ticks.
  30441. if (!tickModel.get('show') || axis.scale.isBlank()) {
  30442. ticks = [];
  30443. }
  30444. if (isFunction$1(optionTickInterval)) {
  30445. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  30446. }
  30447. // Always use label interval by default despite label show. Consider this
  30448. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  30449. // labels. `splitLine` and `axisTick` should be consistent in this case.
  30450. else if (optionTickInterval === 'auto') {
  30451. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  30452. tickCategoryInterval = labelsResult.labelCategoryInterval;
  30453. ticks = map(labelsResult.labels, function (labelItem) {
  30454. return labelItem.tickValue;
  30455. });
  30456. }
  30457. else {
  30458. tickCategoryInterval = optionTickInterval;
  30459. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  30460. }
  30461. // Cache to avoid calling interval function repeatly.
  30462. return listCacheSet(ticksCache, optionTickInterval, {
  30463. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  30464. });
  30465. }
  30466. function makeRealNumberLabels(axis) {
  30467. var ticks = axis.scale.getTicks();
  30468. var labelFormatter = makeLabelFormatter(axis);
  30469. return {
  30470. labels: map(ticks, function (tickValue, idx) {
  30471. return {
  30472. formattedLabel: labelFormatter(tickValue, idx),
  30473. rawLabel: axis.scale.getLabel(tickValue),
  30474. tickValue: tickValue
  30475. };
  30476. })
  30477. };
  30478. }
  30479. // Large category data calculation is performence sensitive, and ticks and label
  30480. // probably be fetched by multiple times. So we cache the result.
  30481. // axis is created each time during a ec process, so we do not need to clear cache.
  30482. function getListCache(axis, prop) {
  30483. // Because key can be funciton, and cache size always be small, we use array cache.
  30484. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  30485. }
  30486. function listCacheGet(cache, key) {
  30487. for (var i = 0; i < cache.length; i++) {
  30488. if (cache[i].key === key) {
  30489. return cache[i].value;
  30490. }
  30491. }
  30492. }
  30493. function listCacheSet(cache, key, value) {
  30494. cache.push({key: key, value: value});
  30495. return value;
  30496. }
  30497. function makeAutoCategoryInterval(axis) {
  30498. var result = inner$6(axis).autoInterval;
  30499. return result != null
  30500. ? result
  30501. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  30502. }
  30503. /**
  30504. * Calculate interval for category axis ticks and labels.
  30505. * To get precise result, at least one of `getRotate` and `isHorizontal`
  30506. * should be implemented in axis.
  30507. */
  30508. function calculateCategoryInterval(axis) {
  30509. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  30510. var labelFormatter = makeLabelFormatter(axis);
  30511. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  30512. var ordinalScale = axis.scale;
  30513. var ordinalExtent = ordinalScale.getExtent();
  30514. // Providing this method is for optimization:
  30515. // avoid generating a long array by `getTicks`
  30516. // in large category data case.
  30517. var tickCount = ordinalScale.count();
  30518. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  30519. return 0;
  30520. }
  30521. var step = 1;
  30522. // Simple optimization. Empirical value: tick count should less than 40.
  30523. if (tickCount > 40) {
  30524. step = Math.max(1, Math.floor(tickCount / 40));
  30525. }
  30526. var tickValue = ordinalExtent[0];
  30527. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  30528. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  30529. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  30530. var maxW = 0;
  30531. var maxH = 0;
  30532. // Caution: Performance sensitive for large category data.
  30533. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  30534. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  30535. var width = 0;
  30536. var height = 0;
  30537. // Not precise, do not consider align and vertical align
  30538. // and each distance from axis line yet.
  30539. var rect = getBoundingRect(
  30540. labelFormatter(tickValue), params.font, 'center', 'top'
  30541. );
  30542. // Magic number
  30543. width = rect.width * 1.3;
  30544. height = rect.height * 1.3;
  30545. // Min size, void long loop.
  30546. maxW = Math.max(maxW, width, 7);
  30547. maxH = Math.max(maxH, height, 7);
  30548. }
  30549. var dw = maxW / unitW;
  30550. var dh = maxH / unitH;
  30551. // 0/0 is NaN, 1/0 is Infinity.
  30552. isNaN(dw) && (dw = Infinity);
  30553. isNaN(dh) && (dh = Infinity);
  30554. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  30555. var cache = inner$6(axis.model);
  30556. var lastAutoInterval = cache.lastAutoInterval;
  30557. var lastTickCount = cache.lastTickCount;
  30558. // Use cache to keep interval stable while moving zoom window,
  30559. // otherwise the calculated interval might jitter when the zoom
  30560. // window size is close to the interval-changing size.
  30561. if (lastAutoInterval != null
  30562. && lastTickCount != null
  30563. && Math.abs(lastAutoInterval - interval) <= 1
  30564. && Math.abs(lastTickCount - tickCount) <= 1
  30565. // Always choose the bigger one, otherwise the critical
  30566. // point is not the same when zooming in or zooming out.
  30567. && lastAutoInterval > interval
  30568. ) {
  30569. interval = lastAutoInterval;
  30570. }
  30571. // Only update cache if cache not used, otherwise the
  30572. // changing of interval is too insensitive.
  30573. else {
  30574. cache.lastTickCount = tickCount;
  30575. cache.lastAutoInterval = interval;
  30576. }
  30577. return interval;
  30578. }
  30579. function fetchAutoCategoryIntervalCalculationParams(axis) {
  30580. var labelModel = axis.getLabelModel();
  30581. return {
  30582. axisRotate: axis.getRotate
  30583. ? axis.getRotate()
  30584. : (axis.isHorizontal && !axis.isHorizontal())
  30585. ? 90
  30586. : 0,
  30587. labelRotate: labelModel.get('rotate') || 0,
  30588. font: labelModel.getFont()
  30589. };
  30590. }
  30591. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  30592. var labelFormatter = makeLabelFormatter(axis);
  30593. var ordinalScale = axis.scale;
  30594. var ordinalExtent = ordinalScale.getExtent();
  30595. var labelModel = axis.getLabelModel();
  30596. var result = [];
  30597. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  30598. var step = Math.max((categoryInterval || 0) + 1, 1);
  30599. var startTick = ordinalExtent[0];
  30600. var tickCount = ordinalScale.count();
  30601. // Calculate start tick based on zero if possible to keep label consistent
  30602. // while zooming and moving while interval > 0. Otherwise the selection
  30603. // of displayable ticks and symbols probably keep changing.
  30604. // 3 is empirical value.
  30605. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  30606. startTick = Math.round(Math.ceil(startTick / step) * step);
  30607. }
  30608. // (1) Only add min max label here but leave overlap checking
  30609. // to render stage, which also ensure the returned list
  30610. // suitable for splitLine and splitArea rendering.
  30611. // (2) Scales except category always contain min max label so
  30612. // do not need to perform this process.
  30613. var showAllLabel = shouldShowAllLabels(axis);
  30614. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  30615. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  30616. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  30617. addItem(ordinalExtent[0]);
  30618. }
  30619. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  30620. var tickValue = startTick;
  30621. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  30622. addItem(tickValue);
  30623. }
  30624. if (includeMaxLabel && tickValue !== ordinalExtent[1]) {
  30625. addItem(ordinalExtent[1]);
  30626. }
  30627. function addItem(tVal) {
  30628. result.push(onlyTick
  30629. ? tVal
  30630. : {
  30631. formattedLabel: labelFormatter(tVal),
  30632. rawLabel: ordinalScale.getLabel(tVal),
  30633. tickValue: tVal
  30634. }
  30635. );
  30636. }
  30637. return result;
  30638. }
  30639. // When interval is function, the result `false` means ignore the tick.
  30640. // It is time consuming for large category data.
  30641. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  30642. var ordinalScale = axis.scale;
  30643. var labelFormatter = makeLabelFormatter(axis);
  30644. var result = [];
  30645. each$1(ordinalScale.getTicks(), function (tickValue) {
  30646. var rawLabel = ordinalScale.getLabel(tickValue);
  30647. if (categoryInterval(tickValue, rawLabel)) {
  30648. result.push(onlyTick
  30649. ? tickValue
  30650. : {
  30651. formattedLabel: labelFormatter(tickValue),
  30652. rawLabel: rawLabel,
  30653. tickValue: tickValue
  30654. }
  30655. );
  30656. }
  30657. });
  30658. return result;
  30659. }
  30660. /*
  30661. * Licensed to the Apache Software Foundation (ASF) under one
  30662. * or more contributor license agreements. See the NOTICE file
  30663. * distributed with this work for additional information
  30664. * regarding copyright ownership. The ASF licenses this file
  30665. * to you under the Apache License, Version 2.0 (the
  30666. * "License"); you may not use this file except in compliance
  30667. * with the License. You may obtain a copy of the License at
  30668. *
  30669. * http://www.apache.org/licenses/LICENSE-2.0
  30670. *
  30671. * Unless required by applicable law or agreed to in writing,
  30672. * software distributed under the License is distributed on an
  30673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30674. * KIND, either express or implied. See the License for the
  30675. * specific language governing permissions and limitations
  30676. * under the License.
  30677. */
  30678. var NORMALIZED_EXTENT = [0, 1];
  30679. /**
  30680. * Base class of Axis.
  30681. * @constructor
  30682. */
  30683. var Axis = function (dim, scale, extent) {
  30684. /**
  30685. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  30686. * @type {string}
  30687. */
  30688. this.dim = dim;
  30689. /**
  30690. * Axis scale
  30691. * @type {module:echarts/coord/scale/*}
  30692. */
  30693. this.scale = scale;
  30694. /**
  30695. * @type {Array.<number>}
  30696. * @private
  30697. */
  30698. this._extent = extent || [0, 0];
  30699. /**
  30700. * @type {boolean}
  30701. */
  30702. this.inverse = false;
  30703. /**
  30704. * Usually true when axis has a ordinal scale
  30705. * @type {boolean}
  30706. */
  30707. this.onBand = false;
  30708. };
  30709. Axis.prototype = {
  30710. constructor: Axis,
  30711. /**
  30712. * If axis extent contain given coord
  30713. * @param {number} coord
  30714. * @return {boolean}
  30715. */
  30716. contain: function (coord) {
  30717. var extent = this._extent;
  30718. var min = Math.min(extent[0], extent[1]);
  30719. var max = Math.max(extent[0], extent[1]);
  30720. return coord >= min && coord <= max;
  30721. },
  30722. /**
  30723. * If axis extent contain given data
  30724. * @param {number} data
  30725. * @return {boolean}
  30726. */
  30727. containData: function (data) {
  30728. return this.contain(this.dataToCoord(data));
  30729. },
  30730. /**
  30731. * Get coord extent.
  30732. * @return {Array.<number>}
  30733. */
  30734. getExtent: function () {
  30735. return this._extent.slice();
  30736. },
  30737. /**
  30738. * Get precision used for formatting
  30739. * @param {Array.<number>} [dataExtent]
  30740. * @return {number}
  30741. */
  30742. getPixelPrecision: function (dataExtent) {
  30743. return getPixelPrecision(
  30744. dataExtent || this.scale.getExtent(),
  30745. this._extent
  30746. );
  30747. },
  30748. /**
  30749. * Set coord extent
  30750. * @param {number} start
  30751. * @param {number} end
  30752. */
  30753. setExtent: function (start, end) {
  30754. var extent = this._extent;
  30755. extent[0] = start;
  30756. extent[1] = end;
  30757. },
  30758. /**
  30759. * Convert data to coord. Data is the rank if it has an ordinal scale
  30760. * @param {number} data
  30761. * @param {boolean} clamp
  30762. * @return {number}
  30763. */
  30764. dataToCoord: function (data, clamp) {
  30765. var extent = this._extent;
  30766. var scale = this.scale;
  30767. data = scale.normalize(data);
  30768. if (this.onBand && scale.type === 'ordinal') {
  30769. extent = extent.slice();
  30770. fixExtentWithBands(extent, scale.count());
  30771. }
  30772. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  30773. },
  30774. /**
  30775. * Convert coord to data. Data is the rank if it has an ordinal scale
  30776. * @param {number} coord
  30777. * @param {boolean} clamp
  30778. * @return {number}
  30779. */
  30780. coordToData: function (coord, clamp) {
  30781. var extent = this._extent;
  30782. var scale = this.scale;
  30783. if (this.onBand && scale.type === 'ordinal') {
  30784. extent = extent.slice();
  30785. fixExtentWithBands(extent, scale.count());
  30786. }
  30787. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  30788. return this.scale.scale(t);
  30789. },
  30790. /**
  30791. * Convert pixel point to data in axis
  30792. * @param {Array.<number>} point
  30793. * @param {boolean} clamp
  30794. * @return {number} data
  30795. */
  30796. pointToData: function (point, clamp) {
  30797. // Should be implemented in derived class if necessary.
  30798. },
  30799. /**
  30800. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  30801. * `axis.getTicksCoords` considers `onBand`, which is used by
  30802. * `boundaryGap:true` of category axis and splitLine and splitArea.
  30803. * @param {Object} [opt]
  30804. * @param {number} [opt.tickModel=axis.model.getModel('axisTick')]
  30805. * @param {boolean} [opt.clamp] If `true`, the first and the last
  30806. * tick must be at the axis end points. Otherwise, clip ticks
  30807. * that outside the axis extent.
  30808. * @return {Array.<Object>} [{
  30809. * coord: ...,
  30810. * tickValue: ...
  30811. * }, ...]
  30812. */
  30813. getTicksCoords: function (opt) {
  30814. opt = opt || {};
  30815. var tickModel = opt.tickModel || this.getTickModel();
  30816. var result = createAxisTicks(this, tickModel);
  30817. var ticks = result.ticks;
  30818. var ticksCoords = map(ticks, function (tickValue) {
  30819. return {
  30820. coord: this.dataToCoord(tickValue),
  30821. tickValue: tickValue
  30822. };
  30823. }, this);
  30824. var alignWithLabel = tickModel.get('alignWithLabel');
  30825. fixOnBandTicksCoords(
  30826. this, ticksCoords, result.tickCategoryInterval, alignWithLabel, opt.clamp
  30827. );
  30828. return ticksCoords;
  30829. },
  30830. /**
  30831. * @return {Array.<Object>} [{
  30832. * formattedLabel: string,
  30833. * rawLabel: axis.scale.getLabel(tickValue)
  30834. * tickValue: number
  30835. * }, ...]
  30836. */
  30837. getViewLabels: function () {
  30838. return createAxisLabels(this).labels;
  30839. },
  30840. /**
  30841. * @return {module:echarts/coord/model/Model}
  30842. */
  30843. getLabelModel: function () {
  30844. return this.model.getModel('axisLabel');
  30845. },
  30846. /**
  30847. * Notice here we only get the default tick model. For splitLine
  30848. * or splitArea, we should pass the splitLineModel or splitAreaModel
  30849. * manually when calling `getTicksCoords`.
  30850. * In GL, this method may be overrided to:
  30851. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  30852. * @return {module:echarts/coord/model/Model}
  30853. */
  30854. getTickModel: function () {
  30855. return this.model.getModel('axisTick');
  30856. },
  30857. /**
  30858. * Get width of band
  30859. * @return {number}
  30860. */
  30861. getBandWidth: function () {
  30862. var axisExtent = this._extent;
  30863. var dataExtent = this.scale.getExtent();
  30864. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  30865. // Fix #2728, avoid NaN when only one data.
  30866. len === 0 && (len = 1);
  30867. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  30868. return Math.abs(size) / len;
  30869. },
  30870. /**
  30871. * @abstract
  30872. * @return {boolean} Is horizontal
  30873. */
  30874. isHorizontal: null,
  30875. /**
  30876. * @abstract
  30877. * @return {number} Get axis rotate, by degree.
  30878. */
  30879. getRotate: null,
  30880. /**
  30881. * Only be called in category axis.
  30882. * Can be overrided, consider other axes like in 3D.
  30883. * @return {number} Auto interval for cateogry axis tick and label
  30884. */
  30885. calculateCategoryInterval: function () {
  30886. return calculateCategoryInterval(this);
  30887. }
  30888. };
  30889. function fixExtentWithBands(extent, nTick) {
  30890. var size = extent[1] - extent[0];
  30891. var len = nTick;
  30892. var margin = size / len / 2;
  30893. extent[0] += margin;
  30894. extent[1] -= margin;
  30895. }
  30896. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  30897. // |---1---|---2---|---3---|---4---|.
  30898. // So the displayed ticks and splitLine/splitArea should between
  30899. // each data item, otherwise cause misleading (e.g., split tow bars
  30900. // of a single data item when there are two bar series).
  30901. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  30902. // splitLine/spliteArea should layout appropriately corresponding
  30903. // to displayed labels. (So we should not use `getBandWidth` in this
  30904. // case).
  30905. function fixOnBandTicksCoords(axis, ticksCoords, tickCategoryInterval, alignWithLabel, clamp) {
  30906. var ticksLen = ticksCoords.length;
  30907. if (!axis.onBand || alignWithLabel || !ticksLen) {
  30908. return;
  30909. }
  30910. var axisExtent = axis.getExtent();
  30911. var last;
  30912. if (ticksLen === 1) {
  30913. ticksCoords[0].coord = axisExtent[0];
  30914. last = ticksCoords[1] = {coord: axisExtent[0]};
  30915. }
  30916. else {
  30917. var shift = (ticksCoords[1].coord - ticksCoords[0].coord);
  30918. each$1(ticksCoords, function (ticksItem) {
  30919. ticksItem.coord -= shift / 2;
  30920. var tickCategoryInterval = tickCategoryInterval || 0;
  30921. // Avoid split a single data item when odd interval.
  30922. if (tickCategoryInterval % 2 > 0) {
  30923. ticksItem.coord -= shift / ((tickCategoryInterval + 1) * 2);
  30924. }
  30925. });
  30926. last = {coord: ticksCoords[ticksLen - 1].coord + shift};
  30927. ticksCoords.push(last);
  30928. }
  30929. var inverse = axisExtent[0] > axisExtent[1];
  30930. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  30931. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  30932. }
  30933. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  30934. ticksCoords.unshift({coord: axisExtent[0]});
  30935. }
  30936. if (littleThan(axisExtent[1], last.coord)) {
  30937. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  30938. }
  30939. if (clamp && littleThan(last.coord, axisExtent[1])) {
  30940. ticksCoords.push({coord: axisExtent[1]});
  30941. }
  30942. function littleThan(a, b) {
  30943. return inverse ? a > b : a < b;
  30944. }
  30945. }
  30946. /*
  30947. * Licensed to the Apache Software Foundation (ASF) under one
  30948. * or more contributor license agreements. See the NOTICE file
  30949. * distributed with this work for additional information
  30950. * regarding copyright ownership. The ASF licenses this file
  30951. * to you under the Apache License, Version 2.0 (the
  30952. * "License"); you may not use this file except in compliance
  30953. * with the License. You may obtain a copy of the License at
  30954. *
  30955. * http://www.apache.org/licenses/LICENSE-2.0
  30956. *
  30957. * Unless required by applicable law or agreed to in writing,
  30958. * software distributed under the License is distributed on an
  30959. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30960. * KIND, either express or implied. See the License for the
  30961. * specific language governing permissions and limitations
  30962. * under the License.
  30963. */
  30964. /**
  30965. * Do not mount those modules on 'src/echarts' for better tree shaking.
  30966. */
  30967. var parseGeoJson = parseGeoJson$1;
  30968. var ecUtil = {};
  30969. each$1(
  30970. [
  30971. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  30972. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  30973. 'extend', 'defaults', 'clone', 'merge'
  30974. ],
  30975. function (name) {
  30976. ecUtil[name] = zrUtil[name];
  30977. }
  30978. );
  30979. var graphic$1 = {};
  30980. each$1(
  30981. [
  30982. 'extendShape', 'extendPath', 'makePath', 'makeImage',
  30983. 'mergePath', 'resizePath', 'createIcon',
  30984. 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText',
  30985. 'getFont', 'updateProps', 'initProps', 'getTransform',
  30986. 'clipPointsByRect', 'clipRectByRect',
  30987. 'Group',
  30988. 'Image',
  30989. 'Text',
  30990. 'Circle',
  30991. 'Sector',
  30992. 'Ring',
  30993. 'Polygon',
  30994. 'Polyline',
  30995. 'Rect',
  30996. 'Line',
  30997. 'BezierCurve',
  30998. 'Arc',
  30999. 'IncrementalDisplayable',
  31000. 'CompoundPath',
  31001. 'LinearGradient',
  31002. 'RadialGradient',
  31003. 'BoundingRect'
  31004. ],
  31005. function (name) {
  31006. graphic$1[name] = graphic[name];
  31007. }
  31008. );
  31009. /*
  31010. * Licensed to the Apache Software Foundation (ASF) under one
  31011. * or more contributor license agreements. See the NOTICE file
  31012. * distributed with this work for additional information
  31013. * regarding copyright ownership. The ASF licenses this file
  31014. * to you under the Apache License, Version 2.0 (the
  31015. * "License"); you may not use this file except in compliance
  31016. * with the License. You may obtain a copy of the License at
  31017. *
  31018. * http://www.apache.org/licenses/LICENSE-2.0
  31019. *
  31020. * Unless required by applicable law or agreed to in writing,
  31021. * software distributed under the License is distributed on an
  31022. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31023. * KIND, either express or implied. See the License for the
  31024. * specific language governing permissions and limitations
  31025. * under the License.
  31026. */
  31027. SeriesModel.extend({
  31028. type: 'series.line',
  31029. dependencies: ['grid', 'polar'],
  31030. getInitialData: function (option, ecModel) {
  31031. if (__DEV__) {
  31032. var coordSys = option.coordinateSystem;
  31033. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  31034. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  31035. }
  31036. }
  31037. return createListFromArray(this.getSource(), this);
  31038. },
  31039. defaultOption: {
  31040. zlevel: 0,
  31041. z: 2,
  31042. coordinateSystem: 'cartesian2d',
  31043. legendHoverLink: true,
  31044. hoverAnimation: true,
  31045. // stack: null
  31046. // xAxisIndex: 0,
  31047. // yAxisIndex: 0,
  31048. // polarIndex: 0,
  31049. // If clip the overflow value
  31050. clipOverflow: true,
  31051. // cursor: null,
  31052. label: {
  31053. position: 'top'
  31054. },
  31055. // itemStyle: {
  31056. // },
  31057. lineStyle: {
  31058. width: 2,
  31059. type: 'solid'
  31060. },
  31061. // areaStyle: {
  31062. // origin of areaStyle. Valid values:
  31063. // `'auto'/null/undefined`: from axisLine to data
  31064. // `'start'`: from min to data
  31065. // `'end'`: from data to max
  31066. // origin: 'auto'
  31067. // },
  31068. // false, 'start', 'end', 'middle'
  31069. step: false,
  31070. // Disabled if step is true
  31071. smooth: false,
  31072. smoothMonotone: null,
  31073. symbol: 'emptyCircle',
  31074. symbolSize: 4,
  31075. symbolRotate: null,
  31076. showSymbol: true,
  31077. // `false`: follow the label interval strategy.
  31078. // `true`: show all symbols.
  31079. // `'auto'`: If possible, show all symbols, otherwise
  31080. // follow the label interval strategy.
  31081. showAllSymbol: 'auto',
  31082. // Whether to connect break point.
  31083. connectNulls: false,
  31084. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  31085. sampling: 'none',
  31086. animationEasing: 'linear',
  31087. // Disable progressive
  31088. progressive: 0,
  31089. hoverLayerThreshold: Infinity
  31090. }
  31091. });
  31092. /*
  31093. * Licensed to the Apache Software Foundation (ASF) under one
  31094. * or more contributor license agreements. See the NOTICE file
  31095. * distributed with this work for additional information
  31096. * regarding copyright ownership. The ASF licenses this file
  31097. * to you under the Apache License, Version 2.0 (the
  31098. * "License"); you may not use this file except in compliance
  31099. * with the License. You may obtain a copy of the License at
  31100. *
  31101. * http://www.apache.org/licenses/LICENSE-2.0
  31102. *
  31103. * Unless required by applicable law or agreed to in writing,
  31104. * software distributed under the License is distributed on an
  31105. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31106. * KIND, either express or implied. See the License for the
  31107. * specific language governing permissions and limitations
  31108. * under the License.
  31109. */
  31110. /**
  31111. * @param {module:echarts/data/List} data
  31112. * @param {number} dataIndex
  31113. * @return {string} label string. Not null/undefined
  31114. */
  31115. function getDefaultLabel(data, dataIndex) {
  31116. var labelDims = data.mapDimension('defaultedLabel', true);
  31117. var len = labelDims.length;
  31118. // Simple optimization (in lots of cases, label dims length is 1)
  31119. if (len === 1) {
  31120. return retrieveRawValue(data, dataIndex, labelDims[0]);
  31121. }
  31122. else if (len) {
  31123. var vals = [];
  31124. for (var i = 0; i < labelDims.length; i++) {
  31125. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  31126. vals.push(val);
  31127. }
  31128. return vals.join(' ');
  31129. }
  31130. }
  31131. /*
  31132. * Licensed to the Apache Software Foundation (ASF) under one
  31133. * or more contributor license agreements. See the NOTICE file
  31134. * distributed with this work for additional information
  31135. * regarding copyright ownership. The ASF licenses this file
  31136. * to you under the Apache License, Version 2.0 (the
  31137. * "License"); you may not use this file except in compliance
  31138. * with the License. You may obtain a copy of the License at
  31139. *
  31140. * http://www.apache.org/licenses/LICENSE-2.0
  31141. *
  31142. * Unless required by applicable law or agreed to in writing,
  31143. * software distributed under the License is distributed on an
  31144. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31145. * KIND, either express or implied. See the License for the
  31146. * specific language governing permissions and limitations
  31147. * under the License.
  31148. */
  31149. /**
  31150. * @module echarts/chart/helper/Symbol
  31151. */
  31152. /**
  31153. * @constructor
  31154. * @alias {module:echarts/chart/helper/Symbol}
  31155. * @param {module:echarts/data/List} data
  31156. * @param {number} idx
  31157. * @extends {module:zrender/graphic/Group}
  31158. */
  31159. function SymbolClz$1(data, idx, seriesScope) {
  31160. Group.call(this);
  31161. this.updateData(data, idx, seriesScope);
  31162. }
  31163. var symbolProto = SymbolClz$1.prototype;
  31164. /**
  31165. * @public
  31166. * @static
  31167. * @param {module:echarts/data/List} data
  31168. * @param {number} dataIndex
  31169. * @return {Array.<number>} [width, height]
  31170. */
  31171. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  31172. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  31173. return symbolSize instanceof Array
  31174. ? symbolSize.slice()
  31175. : [+symbolSize, +symbolSize];
  31176. };
  31177. function getScale(symbolSize) {
  31178. return [symbolSize[0] / 2, symbolSize[1] / 2];
  31179. }
  31180. function driftSymbol(dx, dy) {
  31181. this.parent.drift(dx, dy);
  31182. }
  31183. symbolProto._createSymbol = function (
  31184. symbolType,
  31185. data,
  31186. idx,
  31187. symbolSize,
  31188. keepAspect
  31189. ) {
  31190. // Remove paths created before
  31191. this.removeAll();
  31192. var color = data.getItemVisual(idx, 'color');
  31193. // var symbolPath = createSymbol(
  31194. // symbolType, -0.5, -0.5, 1, 1, color
  31195. // );
  31196. // If width/height are set too small (e.g., set to 1) on ios10
  31197. // and macOS Sierra, a circle stroke become a rect, no matter what
  31198. // the scale is set. So we set width/height as 2. See #4150.
  31199. var symbolPath = createSymbol(
  31200. symbolType, -1, -1, 2, 2, color, keepAspect
  31201. );
  31202. symbolPath.attr({
  31203. z2: 100,
  31204. culling: true,
  31205. scale: getScale(symbolSize)
  31206. });
  31207. // Rewrite drift method
  31208. symbolPath.drift = driftSymbol;
  31209. this._symbolType = symbolType;
  31210. this.add(symbolPath);
  31211. };
  31212. /**
  31213. * Stop animation
  31214. * @param {boolean} toLastFrame
  31215. */
  31216. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  31217. this.childAt(0).stopAnimation(toLastFrame);
  31218. };
  31219. /**
  31220. * FIXME:
  31221. * Caution: This method breaks the encapsulation of this module,
  31222. * but it indeed brings convenience. So do not use the method
  31223. * unless you detailedly know all the implements of `Symbol`,
  31224. * especially animation.
  31225. *
  31226. * Get symbol path element.
  31227. */
  31228. symbolProto.getSymbolPath = function () {
  31229. return this.childAt(0);
  31230. };
  31231. /**
  31232. * Get scale(aka, current symbol size).
  31233. * Including the change caused by animation
  31234. */
  31235. symbolProto.getScale = function () {
  31236. return this.childAt(0).scale;
  31237. };
  31238. /**
  31239. * Highlight symbol
  31240. */
  31241. symbolProto.highlight = function () {
  31242. this.childAt(0).trigger('emphasis');
  31243. };
  31244. /**
  31245. * Downplay symbol
  31246. */
  31247. symbolProto.downplay = function () {
  31248. this.childAt(0).trigger('normal');
  31249. };
  31250. /**
  31251. * @param {number} zlevel
  31252. * @param {number} z
  31253. */
  31254. symbolProto.setZ = function (zlevel, z) {
  31255. var symbolPath = this.childAt(0);
  31256. symbolPath.zlevel = zlevel;
  31257. symbolPath.z = z;
  31258. };
  31259. symbolProto.setDraggable = function (draggable) {
  31260. var symbolPath = this.childAt(0);
  31261. symbolPath.draggable = draggable;
  31262. symbolPath.cursor = draggable ? 'move' : 'pointer';
  31263. };
  31264. /**
  31265. * Update symbol properties
  31266. * @param {module:echarts/data/List} data
  31267. * @param {number} idx
  31268. * @param {Object} [seriesScope]
  31269. * @param {Object} [seriesScope.itemStyle]
  31270. * @param {Object} [seriesScope.hoverItemStyle]
  31271. * @param {Object} [seriesScope.symbolRotate]
  31272. * @param {Object} [seriesScope.symbolOffset]
  31273. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  31274. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  31275. * @param {boolean} [seriesScope.hoverAnimation]
  31276. * @param {Object} [seriesScope.cursorStyle]
  31277. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  31278. * @param {string} [seriesScope.symbolInnerColor]
  31279. * @param {Object} [seriesScope.fadeIn=false]
  31280. */
  31281. symbolProto.updateData = function (data, idx, seriesScope) {
  31282. this.silent = false;
  31283. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  31284. var seriesModel = data.hostModel;
  31285. var symbolSize = getSymbolSize(data, idx);
  31286. var isInit = symbolType !== this._symbolType;
  31287. if (isInit) {
  31288. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  31289. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  31290. }
  31291. else {
  31292. var symbolPath = this.childAt(0);
  31293. symbolPath.silent = false;
  31294. updateProps(symbolPath, {
  31295. scale: getScale(symbolSize)
  31296. }, seriesModel, idx);
  31297. }
  31298. this._updateCommon(data, idx, symbolSize, seriesScope);
  31299. if (isInit) {
  31300. var symbolPath = this.childAt(0);
  31301. var fadeIn = seriesScope && seriesScope.fadeIn;
  31302. var target = {scale: symbolPath.scale.slice()};
  31303. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  31304. symbolPath.scale = [0, 0];
  31305. fadeIn && (symbolPath.style.opacity = 0);
  31306. initProps(symbolPath, target, seriesModel, idx);
  31307. }
  31308. this._seriesModel = seriesModel;
  31309. };
  31310. // Update common properties
  31311. var normalStyleAccessPath = ['itemStyle'];
  31312. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  31313. var normalLabelAccessPath = ['label'];
  31314. var emphasisLabelAccessPath = ['emphasis', 'label'];
  31315. /**
  31316. * @param {module:echarts/data/List} data
  31317. * @param {number} idx
  31318. * @param {Array.<number>} symbolSize
  31319. * @param {Object} [seriesScope]
  31320. */
  31321. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  31322. var symbolPath = this.childAt(0);
  31323. var seriesModel = data.hostModel;
  31324. var color = data.getItemVisual(idx, 'color');
  31325. // Reset style
  31326. if (symbolPath.type !== 'image') {
  31327. symbolPath.useStyle({
  31328. strokeNoScale: true
  31329. });
  31330. }
  31331. var itemStyle = seriesScope && seriesScope.itemStyle;
  31332. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  31333. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  31334. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  31335. var labelModel = seriesScope && seriesScope.labelModel;
  31336. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  31337. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  31338. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  31339. if (!seriesScope || data.hasItemOption) {
  31340. var itemModel = (seriesScope && seriesScope.itemModel)
  31341. ? seriesScope.itemModel : data.getItemModel(idx);
  31342. // Color must be excluded.
  31343. // Because symbol provide setColor individually to set fill and stroke
  31344. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  31345. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  31346. symbolRotate = itemModel.getShallow('symbolRotate');
  31347. symbolOffset = itemModel.getShallow('symbolOffset');
  31348. labelModel = itemModel.getModel(normalLabelAccessPath);
  31349. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  31350. hoverAnimation = itemModel.getShallow('hoverAnimation');
  31351. cursorStyle = itemModel.getShallow('cursor');
  31352. }
  31353. else {
  31354. hoverItemStyle = extend({}, hoverItemStyle);
  31355. }
  31356. var elStyle = symbolPath.style;
  31357. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  31358. if (symbolOffset) {
  31359. symbolPath.attr('position', [
  31360. parsePercent$1(symbolOffset[0], symbolSize[0]),
  31361. parsePercent$1(symbolOffset[1], symbolSize[1])
  31362. ]);
  31363. }
  31364. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  31365. // PENDING setColor before setStyle!!!
  31366. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  31367. symbolPath.setStyle(itemStyle);
  31368. var opacity = data.getItemVisual(idx, 'opacity');
  31369. if (opacity != null) {
  31370. elStyle.opacity = opacity;
  31371. }
  31372. var liftZ = data.getItemVisual(idx, 'liftZ');
  31373. var z2Origin = symbolPath.__z2Origin;
  31374. if (liftZ != null) {
  31375. if (z2Origin == null) {
  31376. symbolPath.__z2Origin = symbolPath.z2;
  31377. symbolPath.z2 += liftZ;
  31378. }
  31379. }
  31380. else if (z2Origin != null) {
  31381. symbolPath.z2 = z2Origin;
  31382. symbolPath.__z2Origin = null;
  31383. }
  31384. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  31385. setLabelStyle(
  31386. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  31387. {
  31388. labelFetcher: seriesModel,
  31389. labelDataIndex: idx,
  31390. defaultText: getLabelDefaultText,
  31391. isRectText: true,
  31392. autoColor: color
  31393. }
  31394. );
  31395. // Do not execute util needed.
  31396. function getLabelDefaultText(idx, opt) {
  31397. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  31398. }
  31399. symbolPath.off('mouseover')
  31400. .off('mouseout')
  31401. .off('emphasis')
  31402. .off('normal');
  31403. symbolPath.hoverStyle = hoverItemStyle;
  31404. // FIXME
  31405. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  31406. setHoverStyle(symbolPath);
  31407. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  31408. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  31409. // Note: consider `off`, should use static function here.
  31410. symbolPath.on('mouseover', onMouseOver)
  31411. .on('mouseout', onMouseOut)
  31412. .on('emphasis', onEmphasis)
  31413. .on('normal', onNormal);
  31414. }
  31415. };
  31416. function onMouseOver() {
  31417. // see comment in `graphic.isInEmphasis`
  31418. !isInEmphasis(this) && onEmphasis.call(this);
  31419. }
  31420. function onMouseOut() {
  31421. // see comment in `graphic.isInEmphasis`
  31422. !isInEmphasis(this) && onNormal.call(this);
  31423. }
  31424. function onEmphasis() {
  31425. // Do not support this hover animation util some scenario required.
  31426. // Animation can only be supported in hover layer when using `el.incremetal`.
  31427. if (this.incremental || this.useHoverLayer) {
  31428. return;
  31429. }
  31430. var scale = this.__symbolOriginalScale;
  31431. var ratio = scale[1] / scale[0];
  31432. this.animateTo({
  31433. scale: [
  31434. Math.max(scale[0] * 1.1, scale[0] + 3),
  31435. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  31436. ]
  31437. }, 400, 'elasticOut');
  31438. }
  31439. function onNormal() {
  31440. if (this.incremental || this.useHoverLayer) {
  31441. return;
  31442. }
  31443. this.animateTo({
  31444. scale: this.__symbolOriginalScale
  31445. }, 400, 'elasticOut');
  31446. }
  31447. /**
  31448. * @param {Function} cb
  31449. * @param {Object} [opt]
  31450. * @param {Object} [opt.keepLabel=true]
  31451. */
  31452. symbolProto.fadeOut = function (cb, opt) {
  31453. var symbolPath = this.childAt(0);
  31454. // Avoid mistaken hover when fading out
  31455. this.silent = symbolPath.silent = true;
  31456. // Not show text when animating
  31457. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  31458. updateProps(
  31459. symbolPath,
  31460. {
  31461. style: {opacity: 0},
  31462. scale: [0, 0]
  31463. },
  31464. this._seriesModel,
  31465. this.dataIndex,
  31466. cb
  31467. );
  31468. };
  31469. inherits(SymbolClz$1, Group);
  31470. /*
  31471. * Licensed to the Apache Software Foundation (ASF) under one
  31472. * or more contributor license agreements. See the NOTICE file
  31473. * distributed with this work for additional information
  31474. * regarding copyright ownership. The ASF licenses this file
  31475. * to you under the Apache License, Version 2.0 (the
  31476. * "License"); you may not use this file except in compliance
  31477. * with the License. You may obtain a copy of the License at
  31478. *
  31479. * http://www.apache.org/licenses/LICENSE-2.0
  31480. *
  31481. * Unless required by applicable law or agreed to in writing,
  31482. * software distributed under the License is distributed on an
  31483. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31484. * KIND, either express or implied. See the License for the
  31485. * specific language governing permissions and limitations
  31486. * under the License.
  31487. */
  31488. /**
  31489. * @module echarts/chart/helper/SymbolDraw
  31490. */
  31491. /**
  31492. * @constructor
  31493. * @alias module:echarts/chart/helper/SymbolDraw
  31494. * @param {module:zrender/graphic/Group} [symbolCtor]
  31495. */
  31496. function SymbolDraw(symbolCtor) {
  31497. this.group = new Group();
  31498. this._symbolCtor = symbolCtor || SymbolClz$1;
  31499. }
  31500. var symbolDrawProto = SymbolDraw.prototype;
  31501. function symbolNeedsDraw(data, point, idx, opt) {
  31502. return point && !isNaN(point[0]) && !isNaN(point[1])
  31503. && !(opt.isIgnore && opt.isIgnore(idx))
  31504. // We do not set clipShape on group, because it will cut part of
  31505. // the symbol element shape. We use the same clip shape here as
  31506. // the line clip.
  31507. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  31508. && data.getItemVisual(idx, 'symbol') !== 'none';
  31509. }
  31510. /**
  31511. * Update symbols draw by new data
  31512. * @param {module:echarts/data/List} data
  31513. * @param {Object} [opt] Or isIgnore
  31514. * @param {Function} [opt.isIgnore]
  31515. * @param {Object} [opt.clipShape]
  31516. */
  31517. symbolDrawProto.updateData = function (data, opt) {
  31518. opt = normalizeUpdateOpt(opt);
  31519. var group = this.group;
  31520. var seriesModel = data.hostModel;
  31521. var oldData = this._data;
  31522. var SymbolCtor = this._symbolCtor;
  31523. var seriesScope = makeSeriesScope(data);
  31524. // There is no oldLineData only when first rendering or switching from
  31525. // stream mode to normal mode, where previous elements should be removed.
  31526. if (!oldData) {
  31527. group.removeAll();
  31528. }
  31529. data.diff(oldData)
  31530. .add(function (newIdx) {
  31531. var point = data.getItemLayout(newIdx);
  31532. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  31533. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  31534. symbolEl.attr('position', point);
  31535. data.setItemGraphicEl(newIdx, symbolEl);
  31536. group.add(symbolEl);
  31537. }
  31538. })
  31539. .update(function (newIdx, oldIdx) {
  31540. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  31541. var point = data.getItemLayout(newIdx);
  31542. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  31543. group.remove(symbolEl);
  31544. return;
  31545. }
  31546. if (!symbolEl) {
  31547. symbolEl = new SymbolCtor(data, newIdx);
  31548. symbolEl.attr('position', point);
  31549. }
  31550. else {
  31551. symbolEl.updateData(data, newIdx, seriesScope);
  31552. updateProps(symbolEl, {
  31553. position: point
  31554. }, seriesModel);
  31555. }
  31556. // Add back
  31557. group.add(symbolEl);
  31558. data.setItemGraphicEl(newIdx, symbolEl);
  31559. })
  31560. .remove(function (oldIdx) {
  31561. var el = oldData.getItemGraphicEl(oldIdx);
  31562. el && el.fadeOut(function () {
  31563. group.remove(el);
  31564. });
  31565. })
  31566. .execute();
  31567. this._data = data;
  31568. };
  31569. symbolDrawProto.isPersistent = function () {
  31570. return true;
  31571. };
  31572. symbolDrawProto.updateLayout = function () {
  31573. var data = this._data;
  31574. if (data) {
  31575. // Not use animation
  31576. data.eachItemGraphicEl(function (el, idx) {
  31577. var point = data.getItemLayout(idx);
  31578. el.attr('position', point);
  31579. });
  31580. }
  31581. };
  31582. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  31583. this._seriesScope = makeSeriesScope(data);
  31584. this._data = null;
  31585. this.group.removeAll();
  31586. };
  31587. /**
  31588. * Update symbols draw by new data
  31589. * @param {module:echarts/data/List} data
  31590. * @param {Object} [opt] Or isIgnore
  31591. * @param {Function} [opt.isIgnore]
  31592. * @param {Object} [opt.clipShape]
  31593. */
  31594. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  31595. opt = normalizeUpdateOpt(opt);
  31596. function updateIncrementalAndHover(el) {
  31597. if (!el.isGroup) {
  31598. el.incremental = el.useHoverLayer = true;
  31599. }
  31600. }
  31601. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  31602. var point = data.getItemLayout(idx);
  31603. if (symbolNeedsDraw(data, point, idx, opt)) {
  31604. var el = new this._symbolCtor(data, idx, this._seriesScope);
  31605. el.traverse(updateIncrementalAndHover);
  31606. el.attr('position', point);
  31607. this.group.add(el);
  31608. data.setItemGraphicEl(idx, el);
  31609. }
  31610. }
  31611. };
  31612. function normalizeUpdateOpt(opt) {
  31613. if (opt != null && !isObject$1(opt)) {
  31614. opt = {isIgnore: opt};
  31615. }
  31616. return opt || {};
  31617. }
  31618. symbolDrawProto.remove = function (enableAnimation) {
  31619. var group = this.group;
  31620. var data = this._data;
  31621. // Incremental model do not have this._data.
  31622. if (data && enableAnimation) {
  31623. data.eachItemGraphicEl(function (el) {
  31624. el.fadeOut(function () {
  31625. group.remove(el);
  31626. });
  31627. });
  31628. }
  31629. else {
  31630. group.removeAll();
  31631. }
  31632. };
  31633. function makeSeriesScope(data) {
  31634. var seriesModel = data.hostModel;
  31635. return {
  31636. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  31637. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  31638. symbolRotate: seriesModel.get('symbolRotate'),
  31639. symbolOffset: seriesModel.get('symbolOffset'),
  31640. hoverAnimation: seriesModel.get('hoverAnimation'),
  31641. labelModel: seriesModel.getModel('label'),
  31642. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  31643. cursorStyle: seriesModel.get('cursor')
  31644. };
  31645. }
  31646. /*
  31647. * Licensed to the Apache Software Foundation (ASF) under one
  31648. * or more contributor license agreements. See the NOTICE file
  31649. * distributed with this work for additional information
  31650. * regarding copyright ownership. The ASF licenses this file
  31651. * to you under the Apache License, Version 2.0 (the
  31652. * "License"); you may not use this file except in compliance
  31653. * with the License. You may obtain a copy of the License at
  31654. *
  31655. * http://www.apache.org/licenses/LICENSE-2.0
  31656. *
  31657. * Unless required by applicable law or agreed to in writing,
  31658. * software distributed under the License is distributed on an
  31659. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31660. * KIND, either express or implied. See the License for the
  31661. * specific language governing permissions and limitations
  31662. * under the License.
  31663. */
  31664. /**
  31665. * @param {Object} coordSys
  31666. * @param {module:echarts/data/List} data
  31667. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  31668. */
  31669. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  31670. var baseAxis = coordSys.getBaseAxis();
  31671. var valueAxis = coordSys.getOtherAxis(baseAxis);
  31672. var valueStart = getValueStart(valueAxis, valueOrigin);
  31673. var baseAxisDim = baseAxis.dim;
  31674. var valueAxisDim = valueAxis.dim;
  31675. var valueDim = data.mapDimension(valueAxisDim);
  31676. var baseDim = data.mapDimension(baseAxisDim);
  31677. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  31678. var dims = map(coordSys.dimensions, function (coordDim) {
  31679. return data.mapDimension(coordDim);
  31680. });
  31681. var stacked;
  31682. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  31683. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  31684. dims[0] = stackResultDim;
  31685. }
  31686. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  31687. dims[1] = stackResultDim;
  31688. }
  31689. return {
  31690. dataDimsForPoint: dims,
  31691. valueStart: valueStart,
  31692. valueAxisDim: valueAxisDim,
  31693. baseAxisDim: baseAxisDim,
  31694. stacked: !!stacked,
  31695. valueDim: valueDim,
  31696. baseDim: baseDim,
  31697. baseDataOffset: baseDataOffset,
  31698. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  31699. };
  31700. }
  31701. function getValueStart(valueAxis, valueOrigin) {
  31702. var valueStart = 0;
  31703. var extent = valueAxis.scale.getExtent();
  31704. if (valueOrigin === 'start') {
  31705. valueStart = extent[0];
  31706. }
  31707. else if (valueOrigin === 'end') {
  31708. valueStart = extent[1];
  31709. }
  31710. // auto
  31711. else {
  31712. // Both positive
  31713. if (extent[0] > 0) {
  31714. valueStart = extent[0];
  31715. }
  31716. // Both negative
  31717. else if (extent[1] < 0) {
  31718. valueStart = extent[1];
  31719. }
  31720. // If is one positive, and one negative, onZero shall be true
  31721. }
  31722. return valueStart;
  31723. }
  31724. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  31725. var value = NaN;
  31726. if (dataCoordInfo.stacked) {
  31727. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  31728. }
  31729. if (isNaN(value)) {
  31730. value = dataCoordInfo.valueStart;
  31731. }
  31732. var baseDataOffset = dataCoordInfo.baseDataOffset;
  31733. var stackedData = [];
  31734. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  31735. stackedData[1 - baseDataOffset] = value;
  31736. return coordSys.dataToPoint(stackedData);
  31737. }
  31738. /*
  31739. * Licensed to the Apache Software Foundation (ASF) under one
  31740. * or more contributor license agreements. See the NOTICE file
  31741. * distributed with this work for additional information
  31742. * regarding copyright ownership. The ASF licenses this file
  31743. * to you under the Apache License, Version 2.0 (the
  31744. * "License"); you may not use this file except in compliance
  31745. * with the License. You may obtain a copy of the License at
  31746. *
  31747. * http://www.apache.org/licenses/LICENSE-2.0
  31748. *
  31749. * Unless required by applicable law or agreed to in writing,
  31750. * software distributed under the License is distributed on an
  31751. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31752. * KIND, either express or implied. See the License for the
  31753. * specific language governing permissions and limitations
  31754. * under the License.
  31755. */
  31756. // var arrayDiff = require('zrender/src/core/arrayDiff');
  31757. // 'zrender/src/core/arrayDiff' has been used before, but it did
  31758. // not do well in performance when roam with fixed dataZoom window.
  31759. // function convertToIntId(newIdList, oldIdList) {
  31760. // // Generate int id instead of string id.
  31761. // // Compare string maybe slow in score function of arrDiff
  31762. // // Assume id in idList are all unique
  31763. // var idIndicesMap = {};
  31764. // var idx = 0;
  31765. // for (var i = 0; i < newIdList.length; i++) {
  31766. // idIndicesMap[newIdList[i]] = idx;
  31767. // newIdList[i] = idx++;
  31768. // }
  31769. // for (var i = 0; i < oldIdList.length; i++) {
  31770. // var oldId = oldIdList[i];
  31771. // // Same with newIdList
  31772. // if (idIndicesMap[oldId]) {
  31773. // oldIdList[i] = idIndicesMap[oldId];
  31774. // }
  31775. // else {
  31776. // oldIdList[i] = idx++;
  31777. // }
  31778. // }
  31779. // }
  31780. function diffData(oldData, newData) {
  31781. var diffResult = [];
  31782. newData.diff(oldData)
  31783. .add(function (idx) {
  31784. diffResult.push({cmd: '+', idx: idx});
  31785. })
  31786. .update(function (newIdx, oldIdx) {
  31787. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  31788. })
  31789. .remove(function (idx) {
  31790. diffResult.push({cmd: '-', idx: idx});
  31791. })
  31792. .execute();
  31793. return diffResult;
  31794. }
  31795. var lineAnimationDiff = function (
  31796. oldData, newData,
  31797. oldStackedOnPoints, newStackedOnPoints,
  31798. oldCoordSys, newCoordSys,
  31799. oldValueOrigin, newValueOrigin
  31800. ) {
  31801. var diff = diffData(oldData, newData);
  31802. // var newIdList = newData.mapArray(newData.getId);
  31803. // var oldIdList = oldData.mapArray(oldData.getId);
  31804. // convertToIntId(newIdList, oldIdList);
  31805. // // FIXME One data ?
  31806. // diff = arrayDiff(oldIdList, newIdList);
  31807. var currPoints = [];
  31808. var nextPoints = [];
  31809. // Points for stacking base line
  31810. var currStackedPoints = [];
  31811. var nextStackedPoints = [];
  31812. var status = [];
  31813. var sortedIndices = [];
  31814. var rawIndices = [];
  31815. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  31816. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  31817. for (var i = 0; i < diff.length; i++) {
  31818. var diffItem = diff[i];
  31819. var pointAdded = true;
  31820. // FIXME, animation is not so perfect when dataZoom window moves fast
  31821. // Which is in case remvoing or add more than one data in the tail or head
  31822. switch (diffItem.cmd) {
  31823. case '=':
  31824. var currentPt = oldData.getItemLayout(diffItem.idx);
  31825. var nextPt = newData.getItemLayout(diffItem.idx1);
  31826. // If previous data is NaN, use next point directly
  31827. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  31828. currentPt = nextPt.slice();
  31829. }
  31830. currPoints.push(currentPt);
  31831. nextPoints.push(nextPt);
  31832. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  31833. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  31834. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  31835. break;
  31836. case '+':
  31837. var idx = diffItem.idx;
  31838. currPoints.push(
  31839. oldCoordSys.dataToPoint([
  31840. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  31841. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  31842. ])
  31843. );
  31844. nextPoints.push(newData.getItemLayout(idx).slice());
  31845. currStackedPoints.push(
  31846. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  31847. );
  31848. nextStackedPoints.push(newStackedOnPoints[idx]);
  31849. rawIndices.push(newData.getRawIndex(idx));
  31850. break;
  31851. case '-':
  31852. var idx = diffItem.idx;
  31853. var rawIndex = oldData.getRawIndex(idx);
  31854. // Data is replaced. In the case of dynamic data queue
  31855. // FIXME FIXME FIXME
  31856. if (rawIndex !== idx) {
  31857. currPoints.push(oldData.getItemLayout(idx));
  31858. nextPoints.push(newCoordSys.dataToPoint([
  31859. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  31860. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  31861. ]));
  31862. currStackedPoints.push(oldStackedOnPoints[idx]);
  31863. nextStackedPoints.push(
  31864. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  31865. );
  31866. rawIndices.push(rawIndex);
  31867. }
  31868. else {
  31869. pointAdded = false;
  31870. }
  31871. }
  31872. // Original indices
  31873. if (pointAdded) {
  31874. status.push(diffItem);
  31875. sortedIndices.push(sortedIndices.length);
  31876. }
  31877. }
  31878. // Diff result may be crossed if all items are changed
  31879. // Sort by data index
  31880. sortedIndices.sort(function (a, b) {
  31881. return rawIndices[a] - rawIndices[b];
  31882. });
  31883. var sortedCurrPoints = [];
  31884. var sortedNextPoints = [];
  31885. var sortedCurrStackedPoints = [];
  31886. var sortedNextStackedPoints = [];
  31887. var sortedStatus = [];
  31888. for (var i = 0; i < sortedIndices.length; i++) {
  31889. var idx = sortedIndices[i];
  31890. sortedCurrPoints[i] = currPoints[idx];
  31891. sortedNextPoints[i] = nextPoints[idx];
  31892. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  31893. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  31894. sortedStatus[i] = status[idx];
  31895. }
  31896. return {
  31897. current: sortedCurrPoints,
  31898. next: sortedNextPoints,
  31899. stackedOnCurrent: sortedCurrStackedPoints,
  31900. stackedOnNext: sortedNextStackedPoints,
  31901. status: sortedStatus
  31902. };
  31903. };
  31904. /*
  31905. * Licensed to the Apache Software Foundation (ASF) under one
  31906. * or more contributor license agreements. See the NOTICE file
  31907. * distributed with this work for additional information
  31908. * regarding copyright ownership. The ASF licenses this file
  31909. * to you under the Apache License, Version 2.0 (the
  31910. * "License"); you may not use this file except in compliance
  31911. * with the License. You may obtain a copy of the License at
  31912. *
  31913. * http://www.apache.org/licenses/LICENSE-2.0
  31914. *
  31915. * Unless required by applicable law or agreed to in writing,
  31916. * software distributed under the License is distributed on an
  31917. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31918. * KIND, either express or implied. See the License for the
  31919. * specific language governing permissions and limitations
  31920. * under the License.
  31921. */
  31922. // Poly path support NaN point
  31923. var vec2Min = min;
  31924. var vec2Max = max;
  31925. var scaleAndAdd$1 = scaleAndAdd;
  31926. var v2Copy = copy;
  31927. // Temporary variable
  31928. var v = [];
  31929. var cp0 = [];
  31930. var cp1 = [];
  31931. function isPointNull(p) {
  31932. return isNaN(p[0]) || isNaN(p[1]);
  31933. }
  31934. function drawSegment(
  31935. ctx, points, start, segLen, allLen,
  31936. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  31937. ) {
  31938. // if (smoothMonotone == null) {
  31939. // if (isMono(points, 'x')) {
  31940. // return drawMono(ctx, points, start, segLen, allLen,
  31941. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  31942. // }
  31943. // else if (isMono(points, 'y')) {
  31944. // return drawMono(ctx, points, start, segLen, allLen,
  31945. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  31946. // }
  31947. // else {
  31948. // return drawNonMono.apply(this, arguments);
  31949. // }
  31950. // }
  31951. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  31952. // return drawMono.apply(this, arguments);
  31953. // }
  31954. // else {
  31955. // return drawNonMono.apply(this, arguments);
  31956. // }
  31957. if (smoothMonotone === 'none' || !smoothMonotone) {
  31958. return drawNonMono.apply(this, arguments);
  31959. }
  31960. else {
  31961. return drawMono.apply(this, arguments);
  31962. }
  31963. }
  31964. /**
  31965. * Check if points is in monotone.
  31966. *
  31967. * @param {number[][]} points Array of points which is in [x, y] form
  31968. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  31969. * dimension that is checking.
  31970. * If is 'none', `drawNonMono` should be
  31971. * called.
  31972. * If is undefined, either being monotone
  31973. * in 'x' or 'y' will call `drawMono`.
  31974. */
  31975. // function isMono(points, smoothMonotone) {
  31976. // if (points.length <= 1) {
  31977. // return true;
  31978. // }
  31979. // var dim = smoothMonotone === 'x' ? 0 : 1;
  31980. // var last = points[0][dim];
  31981. // var lastDiff = 0;
  31982. // for (var i = 1; i < points.length; ++i) {
  31983. // var diff = points[i][dim] - last;
  31984. // if (!isNaN(diff) && !isNaN(lastDiff)
  31985. // && diff !== 0 && lastDiff !== 0
  31986. // && ((diff >= 0) !== (lastDiff >= 0))
  31987. // ) {
  31988. // return false;
  31989. // }
  31990. // if (!isNaN(diff) && diff !== 0) {
  31991. // lastDiff = diff;
  31992. // last = points[i][dim];
  31993. // }
  31994. // }
  31995. // return true;
  31996. // }
  31997. /**
  31998. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  31999. * control points will be used. This should be used when points are monotone
  32000. * either in x or y dimension.
  32001. */
  32002. function drawMono(
  32003. ctx, points, start, segLen, allLen,
  32004. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  32005. ) {
  32006. var prevIdx = 0;
  32007. var idx = start;
  32008. for (var k = 0; k < segLen; k++) {
  32009. var p = points[idx];
  32010. if (idx >= allLen || idx < 0) {
  32011. break;
  32012. }
  32013. if (isPointNull(p)) {
  32014. if (connectNulls) {
  32015. idx += dir;
  32016. continue;
  32017. }
  32018. break;
  32019. }
  32020. if (idx === start) {
  32021. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  32022. }
  32023. else {
  32024. if (smooth > 0) {
  32025. var prevP = points[prevIdx];
  32026. var dim = smoothMonotone === 'y' ? 1 : 0;
  32027. // Length of control point to p, either in x or y, but not both
  32028. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  32029. v2Copy(cp0, prevP);
  32030. cp0[dim] = prevP[dim] + ctrlLen;
  32031. v2Copy(cp1, p);
  32032. cp1[dim] = p[dim] - ctrlLen;
  32033. ctx.bezierCurveTo(
  32034. cp0[0], cp0[1],
  32035. cp1[0], cp1[1],
  32036. p[0], p[1]
  32037. );
  32038. }
  32039. else {
  32040. ctx.lineTo(p[0], p[1]);
  32041. }
  32042. }
  32043. prevIdx = idx;
  32044. idx += dir;
  32045. }
  32046. return k;
  32047. }
  32048. /**
  32049. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  32050. * situations. This should be used when points are non-monotone neither in x or
  32051. * y dimension.
  32052. */
  32053. function drawNonMono(
  32054. ctx, points, start, segLen, allLen,
  32055. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  32056. ) {
  32057. var prevIdx = 0;
  32058. var idx = start;
  32059. for (var k = 0; k < segLen; k++) {
  32060. var p = points[idx];
  32061. if (idx >= allLen || idx < 0) {
  32062. break;
  32063. }
  32064. if (isPointNull(p)) {
  32065. if (connectNulls) {
  32066. idx += dir;
  32067. continue;
  32068. }
  32069. break;
  32070. }
  32071. if (idx === start) {
  32072. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  32073. v2Copy(cp0, p);
  32074. }
  32075. else {
  32076. if (smooth > 0) {
  32077. var nextIdx = idx + dir;
  32078. var nextP = points[nextIdx];
  32079. if (connectNulls) {
  32080. // Find next point not null
  32081. while (nextP && isPointNull(points[nextIdx])) {
  32082. nextIdx += dir;
  32083. nextP = points[nextIdx];
  32084. }
  32085. }
  32086. var ratioNextSeg = 0.5;
  32087. var prevP = points[prevIdx];
  32088. var nextP = points[nextIdx];
  32089. // Last point
  32090. if (!nextP || isPointNull(nextP)) {
  32091. v2Copy(cp1, p);
  32092. }
  32093. else {
  32094. // If next data is null in not connect case
  32095. if (isPointNull(nextP) && !connectNulls) {
  32096. nextP = p;
  32097. }
  32098. sub(v, nextP, prevP);
  32099. var lenPrevSeg;
  32100. var lenNextSeg;
  32101. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  32102. var dim = smoothMonotone === 'x' ? 0 : 1;
  32103. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  32104. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  32105. }
  32106. else {
  32107. lenPrevSeg = dist(p, prevP);
  32108. lenNextSeg = dist(p, nextP);
  32109. }
  32110. // Use ratio of seg length
  32111. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  32112. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  32113. }
  32114. // Smooth constraint
  32115. vec2Min(cp0, cp0, smoothMax);
  32116. vec2Max(cp0, cp0, smoothMin);
  32117. vec2Min(cp1, cp1, smoothMax);
  32118. vec2Max(cp1, cp1, smoothMin);
  32119. ctx.bezierCurveTo(
  32120. cp0[0], cp0[1],
  32121. cp1[0], cp1[1],
  32122. p[0], p[1]
  32123. );
  32124. // cp0 of next segment
  32125. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  32126. }
  32127. else {
  32128. ctx.lineTo(p[0], p[1]);
  32129. }
  32130. }
  32131. prevIdx = idx;
  32132. idx += dir;
  32133. }
  32134. return k;
  32135. }
  32136. function getBoundingBox(points, smoothConstraint) {
  32137. var ptMin = [Infinity, Infinity];
  32138. var ptMax = [-Infinity, -Infinity];
  32139. if (smoothConstraint) {
  32140. for (var i = 0; i < points.length; i++) {
  32141. var pt = points[i];
  32142. if (pt[0] < ptMin[0]) {
  32143. ptMin[0] = pt[0];
  32144. }
  32145. if (pt[1] < ptMin[1]) {
  32146. ptMin[1] = pt[1];
  32147. }
  32148. if (pt[0] > ptMax[0]) {
  32149. ptMax[0] = pt[0];
  32150. }
  32151. if (pt[1] > ptMax[1]) {
  32152. ptMax[1] = pt[1];
  32153. }
  32154. }
  32155. }
  32156. return {
  32157. min: smoothConstraint ? ptMin : ptMax,
  32158. max: smoothConstraint ? ptMax : ptMin
  32159. };
  32160. }
  32161. var Polyline$1 = Path.extend({
  32162. type: 'ec-polyline',
  32163. shape: {
  32164. points: [],
  32165. smooth: 0,
  32166. smoothConstraint: true,
  32167. smoothMonotone: null,
  32168. connectNulls: false
  32169. },
  32170. style: {
  32171. fill: null,
  32172. stroke: '#000'
  32173. },
  32174. brush: fixClipWithShadow(Path.prototype.brush),
  32175. buildPath: function (ctx, shape) {
  32176. var points = shape.points;
  32177. var i = 0;
  32178. var len$$1 = points.length;
  32179. var result = getBoundingBox(points, shape.smoothConstraint);
  32180. if (shape.connectNulls) {
  32181. // Must remove first and last null values avoid draw error in polygon
  32182. for (; len$$1 > 0; len$$1--) {
  32183. if (!isPointNull(points[len$$1 - 1])) {
  32184. break;
  32185. }
  32186. }
  32187. for (; i < len$$1; i++) {
  32188. if (!isPointNull(points[i])) {
  32189. break;
  32190. }
  32191. }
  32192. }
  32193. while (i < len$$1) {
  32194. i += drawSegment(
  32195. ctx, points, i, len$$1, len$$1,
  32196. 1, result.min, result.max, shape.smooth,
  32197. shape.smoothMonotone, shape.connectNulls
  32198. ) + 1;
  32199. }
  32200. }
  32201. });
  32202. var Polygon$1 = Path.extend({
  32203. type: 'ec-polygon',
  32204. shape: {
  32205. points: [],
  32206. // Offset between stacked base points and points
  32207. stackedOnPoints: [],
  32208. smooth: 0,
  32209. stackedOnSmooth: 0,
  32210. smoothConstraint: true,
  32211. smoothMonotone: null,
  32212. connectNulls: false
  32213. },
  32214. brush: fixClipWithShadow(Path.prototype.brush),
  32215. buildPath: function (ctx, shape) {
  32216. var points = shape.points;
  32217. var stackedOnPoints = shape.stackedOnPoints;
  32218. var i = 0;
  32219. var len$$1 = points.length;
  32220. var smoothMonotone = shape.smoothMonotone;
  32221. var bbox = getBoundingBox(points, shape.smoothConstraint);
  32222. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  32223. if (shape.connectNulls) {
  32224. // Must remove first and last null values avoid draw error in polygon
  32225. for (; len$$1 > 0; len$$1--) {
  32226. if (!isPointNull(points[len$$1 - 1])) {
  32227. break;
  32228. }
  32229. }
  32230. for (; i < len$$1; i++) {
  32231. if (!isPointNull(points[i])) {
  32232. break;
  32233. }
  32234. }
  32235. }
  32236. while (i < len$$1) {
  32237. var k = drawSegment(
  32238. ctx, points, i, len$$1, len$$1,
  32239. 1, bbox.min, bbox.max, shape.smooth,
  32240. smoothMonotone, shape.connectNulls
  32241. );
  32242. drawSegment(
  32243. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  32244. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  32245. smoothMonotone, shape.connectNulls
  32246. );
  32247. i += k + 1;
  32248. ctx.closePath();
  32249. }
  32250. }
  32251. });
  32252. /*
  32253. * Licensed to the Apache Software Foundation (ASF) under one
  32254. * or more contributor license agreements. See the NOTICE file
  32255. * distributed with this work for additional information
  32256. * regarding copyright ownership. The ASF licenses this file
  32257. * to you under the Apache License, Version 2.0 (the
  32258. * "License"); you may not use this file except in compliance
  32259. * with the License. You may obtain a copy of the License at
  32260. *
  32261. * http://www.apache.org/licenses/LICENSE-2.0
  32262. *
  32263. * Unless required by applicable law or agreed to in writing,
  32264. * software distributed under the License is distributed on an
  32265. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32266. * KIND, either express or implied. See the License for the
  32267. * specific language governing permissions and limitations
  32268. * under the License.
  32269. */
  32270. // FIXME step not support polar
  32271. function isPointsSame(points1, points2) {
  32272. if (points1.length !== points2.length) {
  32273. return;
  32274. }
  32275. for (var i = 0; i < points1.length; i++) {
  32276. var p1 = points1[i];
  32277. var p2 = points2[i];
  32278. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  32279. return;
  32280. }
  32281. }
  32282. return true;
  32283. }
  32284. function getSmooth(smooth) {
  32285. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  32286. }
  32287. function getAxisExtentWithGap(axis) {
  32288. var extent = axis.getGlobalExtent();
  32289. if (axis.onBand) {
  32290. // Remove extra 1px to avoid line miter in clipped edge
  32291. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  32292. var dir = extent[1] > extent[0] ? 1 : -1;
  32293. extent[0] += dir * halfBandWidth;
  32294. extent[1] -= dir * halfBandWidth;
  32295. }
  32296. return extent;
  32297. }
  32298. /**
  32299. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  32300. * @param {module:echarts/data/List} data
  32301. * @param {Object} dataCoordInfo
  32302. * @param {Array.<Array.<number>>} points
  32303. */
  32304. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  32305. if (!dataCoordInfo.valueDim) {
  32306. return [];
  32307. }
  32308. var points = [];
  32309. for (var idx = 0, len = data.count(); idx < len; idx++) {
  32310. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  32311. }
  32312. return points;
  32313. }
  32314. function createGridClipShape(cartesian, hasAnimation, forSymbol, seriesModel) {
  32315. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  32316. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  32317. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  32318. var x = Math.min(xExtent[0], xExtent[1]);
  32319. var y = Math.min(yExtent[0], yExtent[1]);
  32320. var width = Math.max(xExtent[0], xExtent[1]) - x;
  32321. var height = Math.max(yExtent[0], yExtent[1]) - y;
  32322. // Avoid float number rounding error for symbol on the edge of axis extent.
  32323. // See #7913 and `test/dataZoom-clip.html`.
  32324. if (forSymbol) {
  32325. x -= 0.5;
  32326. width += 0.5;
  32327. y -= 0.5;
  32328. height += 0.5;
  32329. }
  32330. else {
  32331. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  32332. // Expand clip shape to avoid clipping when line value exceeds axis
  32333. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  32334. if (isHorizontal) {
  32335. y -= expandSize;
  32336. height += expandSize * 2;
  32337. }
  32338. else {
  32339. x -= expandSize;
  32340. width += expandSize * 2;
  32341. }
  32342. }
  32343. var clipPath = new Rect({
  32344. shape: {
  32345. x: x,
  32346. y: y,
  32347. width: width,
  32348. height: height
  32349. }
  32350. });
  32351. if (hasAnimation) {
  32352. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  32353. initProps(clipPath, {
  32354. shape: {
  32355. width: width,
  32356. height: height
  32357. }
  32358. }, seriesModel);
  32359. }
  32360. return clipPath;
  32361. }
  32362. function createPolarClipShape(polar, hasAnimation, forSymbol, seriesModel) {
  32363. var angleAxis = polar.getAngleAxis();
  32364. var radiusAxis = polar.getRadiusAxis();
  32365. var radiusExtent = radiusAxis.getExtent().slice();
  32366. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  32367. var angleExtent = angleAxis.getExtent();
  32368. var RADIAN = Math.PI / 180;
  32369. // Avoid float number rounding error for symbol on the edge of axis extent.
  32370. if (forSymbol) {
  32371. radiusExtent[0] -= 0.5;
  32372. radiusExtent[1] += 0.5;
  32373. }
  32374. var clipPath = new Sector({
  32375. shape: {
  32376. cx: round$2(polar.cx, 1),
  32377. cy: round$2(polar.cy, 1),
  32378. r0: round$2(radiusExtent[0], 1),
  32379. r: round$2(radiusExtent[1], 1),
  32380. startAngle: -angleExtent[0] * RADIAN,
  32381. endAngle: -angleExtent[1] * RADIAN,
  32382. clockwise: angleAxis.inverse
  32383. }
  32384. });
  32385. if (hasAnimation) {
  32386. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  32387. initProps(clipPath, {
  32388. shape: {
  32389. endAngle: -angleExtent[1] * RADIAN
  32390. }
  32391. }, seriesModel);
  32392. }
  32393. return clipPath;
  32394. }
  32395. function createClipShape(coordSys, hasAnimation, forSymbol, seriesModel) {
  32396. return coordSys.type === 'polar'
  32397. ? createPolarClipShape(coordSys, hasAnimation, forSymbol, seriesModel)
  32398. : createGridClipShape(coordSys, hasAnimation, forSymbol, seriesModel);
  32399. }
  32400. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  32401. var baseAxis = coordSys.getBaseAxis();
  32402. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  32403. var stepPoints = [];
  32404. for (var i = 0; i < points.length - 1; i++) {
  32405. var nextPt = points[i + 1];
  32406. var pt = points[i];
  32407. stepPoints.push(pt);
  32408. var stepPt = [];
  32409. switch (stepTurnAt) {
  32410. case 'end':
  32411. stepPt[baseIndex] = nextPt[baseIndex];
  32412. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  32413. // default is start
  32414. stepPoints.push(stepPt);
  32415. break;
  32416. case 'middle':
  32417. // default is start
  32418. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  32419. var stepPt2 = [];
  32420. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  32421. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  32422. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  32423. stepPoints.push(stepPt);
  32424. stepPoints.push(stepPt2);
  32425. break;
  32426. default:
  32427. stepPt[baseIndex] = pt[baseIndex];
  32428. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  32429. // default is start
  32430. stepPoints.push(stepPt);
  32431. }
  32432. }
  32433. // Last points
  32434. points[i] && stepPoints.push(points[i]);
  32435. return stepPoints;
  32436. }
  32437. function getVisualGradient(data, coordSys) {
  32438. var visualMetaList = data.getVisual('visualMeta');
  32439. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  32440. // When data.count() is 0, gradient range can not be calculated.
  32441. return;
  32442. }
  32443. if (coordSys.type !== 'cartesian2d') {
  32444. if (__DEV__) {
  32445. console.warn('Visual map on line style is only supported on cartesian2d.');
  32446. }
  32447. return;
  32448. }
  32449. var coordDim;
  32450. var visualMeta;
  32451. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  32452. var dimIndex = visualMetaList[i].dimension;
  32453. var dimName = data.dimensions[dimIndex];
  32454. var dimInfo = data.getDimensionInfo(dimName);
  32455. coordDim = dimInfo && dimInfo.coordDim;
  32456. // Can only be x or y
  32457. if (coordDim === 'x' || coordDim === 'y') {
  32458. visualMeta = visualMetaList[i];
  32459. break;
  32460. }
  32461. }
  32462. if (!visualMeta) {
  32463. if (__DEV__) {
  32464. console.warn('Visual map on line style only support x or y dimension.');
  32465. }
  32466. return;
  32467. }
  32468. // If the area to be rendered is bigger than area defined by LinearGradient,
  32469. // the canvas spec prescribes that the color of the first stop and the last
  32470. // stop should be used. But if two stops are added at offset 0, in effect
  32471. // browsers use the color of the second stop to render area outside
  32472. // LinearGradient. So we can only infinitesimally extend area defined in
  32473. // LinearGradient to render `outerColors`.
  32474. var axis = coordSys.getAxis(coordDim);
  32475. // dataToCoor mapping may not be linear, but must be monotonic.
  32476. var colorStops = map(visualMeta.stops, function (stop) {
  32477. return {
  32478. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  32479. color: stop.color
  32480. };
  32481. });
  32482. var stopLen = colorStops.length;
  32483. var outerColors = visualMeta.outerColors.slice();
  32484. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  32485. colorStops.reverse();
  32486. outerColors.reverse();
  32487. }
  32488. var tinyExtent = 10; // Arbitrary value: 10px
  32489. var minCoord = colorStops[0].coord - tinyExtent;
  32490. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  32491. var coordSpan = maxCoord - minCoord;
  32492. if (coordSpan < 1e-3) {
  32493. return 'transparent';
  32494. }
  32495. each$1(colorStops, function (stop) {
  32496. stop.offset = (stop.coord - minCoord) / coordSpan;
  32497. });
  32498. colorStops.push({
  32499. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  32500. color: outerColors[1] || 'transparent'
  32501. });
  32502. colorStops.unshift({ // notice colorStops.length have been changed.
  32503. offset: stopLen ? colorStops[0].offset : 0.5,
  32504. color: outerColors[0] || 'transparent'
  32505. });
  32506. // zrUtil.each(colorStops, function (colorStop) {
  32507. // // Make sure each offset has rounded px to avoid not sharp edge
  32508. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  32509. // });
  32510. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  32511. gradient[coordDim] = minCoord;
  32512. gradient[coordDim + '2'] = maxCoord;
  32513. return gradient;
  32514. }
  32515. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  32516. var showAllSymbol = seriesModel.get('showAllSymbol');
  32517. var isAuto = showAllSymbol === 'auto';
  32518. if (showAllSymbol && !isAuto) {
  32519. return;
  32520. }
  32521. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  32522. if (!categoryAxis) {
  32523. return;
  32524. }
  32525. // Note that category label interval strategy might bring some weird effect
  32526. // in some scenario: users may wonder why some of the symbols are not
  32527. // displayed. So we show all symbols as possible as we can.
  32528. if (isAuto
  32529. // Simplify the logic, do not determine label overlap here.
  32530. && canShowAllSymbolForCategory(categoryAxis, data)
  32531. ) {
  32532. return;
  32533. }
  32534. // Otherwise follow the label interval strategy on category axis.
  32535. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  32536. var labelMap = {};
  32537. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  32538. labelMap[labelItem.tickValue] = 1;
  32539. });
  32540. return function (dataIndex) {
  32541. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  32542. };
  32543. }
  32544. function canShowAllSymbolForCategory(categoryAxis, data) {
  32545. // In mose cases, line is monotonous on category axis, and the label size
  32546. // is close with each other. So we check the symbol size and some of the
  32547. // label size alone with the category axis to estimate whether all symbol
  32548. // can be shown without overlap.
  32549. var axisExtent = categoryAxis.getExtent();
  32550. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  32551. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  32552. // Sampling some points, max 5.
  32553. var dataLen = data.count();
  32554. var step = Math.max(1, Math.round(dataLen / 5));
  32555. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  32556. if (SymbolClz$1.getSymbolSize(
  32557. data, dataIndex
  32558. // Only for cartesian, where `isHorizontal` exists.
  32559. )[categoryAxis.isHorizontal() ? 1 : 0]
  32560. // Empirical number
  32561. * 1.5 > availSize
  32562. ) {
  32563. return false;
  32564. }
  32565. }
  32566. return true;
  32567. }
  32568. Chart.extend({
  32569. type: 'line',
  32570. init: function () {
  32571. var lineGroup = new Group();
  32572. var symbolDraw = new SymbolDraw();
  32573. this.group.add(symbolDraw.group);
  32574. this._symbolDraw = symbolDraw;
  32575. this._lineGroup = lineGroup;
  32576. },
  32577. render: function (seriesModel, ecModel, api) {
  32578. var coordSys = seriesModel.coordinateSystem;
  32579. var group = this.group;
  32580. var data = seriesModel.getData();
  32581. var lineStyleModel = seriesModel.getModel('lineStyle');
  32582. var areaStyleModel = seriesModel.getModel('areaStyle');
  32583. var points = data.mapArray(data.getItemLayout);
  32584. var isCoordSysPolar = coordSys.type === 'polar';
  32585. var prevCoordSys = this._coordSys;
  32586. var symbolDraw = this._symbolDraw;
  32587. var polyline = this._polyline;
  32588. var polygon = this._polygon;
  32589. var lineGroup = this._lineGroup;
  32590. var hasAnimation = seriesModel.get('animation');
  32591. var isAreaChart = !areaStyleModel.isEmpty();
  32592. var valueOrigin = areaStyleModel.get('origin');
  32593. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  32594. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  32595. var showSymbol = seriesModel.get('showSymbol');
  32596. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  32597. && getIsIgnoreFunc(seriesModel, data, coordSys);
  32598. // Remove temporary symbols
  32599. var oldData = this._data;
  32600. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  32601. if (el.__temp) {
  32602. group.remove(el);
  32603. oldData.setItemGraphicEl(idx, null);
  32604. }
  32605. });
  32606. // Remove previous created symbols if showSymbol changed to false
  32607. if (!showSymbol) {
  32608. symbolDraw.remove();
  32609. }
  32610. group.add(lineGroup);
  32611. // FIXME step not support polar
  32612. var step = !isCoordSysPolar && seriesModel.get('step');
  32613. // Initialization animation or coordinate system changed
  32614. if (
  32615. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  32616. ) {
  32617. showSymbol && symbolDraw.updateData(data, {
  32618. isIgnore: isIgnoreFunc,
  32619. clipShape: createClipShape(coordSys, false, true, seriesModel)
  32620. });
  32621. if (step) {
  32622. // TODO If stacked series is not step
  32623. points = turnPointsIntoStep(points, coordSys, step);
  32624. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  32625. }
  32626. polyline = this._newPolyline(points, coordSys, hasAnimation);
  32627. if (isAreaChart) {
  32628. polygon = this._newPolygon(
  32629. points, stackedOnPoints,
  32630. coordSys, hasAnimation
  32631. );
  32632. }
  32633. lineGroup.setClipPath(createClipShape(coordSys, true, false, seriesModel));
  32634. }
  32635. else {
  32636. if (isAreaChart && !polygon) {
  32637. // If areaStyle is added
  32638. polygon = this._newPolygon(
  32639. points, stackedOnPoints,
  32640. coordSys, hasAnimation
  32641. );
  32642. }
  32643. else if (polygon && !isAreaChart) {
  32644. // If areaStyle is removed
  32645. lineGroup.remove(polygon);
  32646. polygon = this._polygon = null;
  32647. }
  32648. // Update clipPath
  32649. lineGroup.setClipPath(createClipShape(coordSys, false, false, seriesModel));
  32650. // Always update, or it is wrong in the case turning on legend
  32651. // because points are not changed
  32652. showSymbol && symbolDraw.updateData(data, {
  32653. isIgnore: isIgnoreFunc,
  32654. clipShape: createClipShape(coordSys, false, true, seriesModel)
  32655. });
  32656. // Stop symbol animation and sync with line points
  32657. // FIXME performance?
  32658. data.eachItemGraphicEl(function (el) {
  32659. el.stopAnimation(true);
  32660. });
  32661. // In the case data zoom triggerred refreshing frequently
  32662. // Data may not change if line has a category axis. So it should animate nothing
  32663. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  32664. || !isPointsSame(this._points, points)
  32665. ) {
  32666. if (hasAnimation) {
  32667. this._updateAnimation(
  32668. data, stackedOnPoints, coordSys, api, step, valueOrigin
  32669. );
  32670. }
  32671. else {
  32672. // Not do it in update with animation
  32673. if (step) {
  32674. // TODO If stacked series is not step
  32675. points = turnPointsIntoStep(points, coordSys, step);
  32676. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  32677. }
  32678. polyline.setShape({
  32679. points: points
  32680. });
  32681. polygon && polygon.setShape({
  32682. points: points,
  32683. stackedOnPoints: stackedOnPoints
  32684. });
  32685. }
  32686. }
  32687. }
  32688. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  32689. polyline.useStyle(defaults(
  32690. // Use color in lineStyle first
  32691. lineStyleModel.getLineStyle(),
  32692. {
  32693. fill: 'none',
  32694. stroke: visualColor,
  32695. lineJoin: 'bevel'
  32696. }
  32697. ));
  32698. var smooth = seriesModel.get('smooth');
  32699. smooth = getSmooth(seriesModel.get('smooth'));
  32700. polyline.setShape({
  32701. smooth: smooth,
  32702. smoothMonotone: seriesModel.get('smoothMonotone'),
  32703. connectNulls: seriesModel.get('connectNulls')
  32704. });
  32705. if (polygon) {
  32706. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  32707. var stackedOnSmooth = 0;
  32708. polygon.useStyle(defaults(
  32709. areaStyleModel.getAreaStyle(),
  32710. {
  32711. fill: visualColor,
  32712. opacity: 0.7,
  32713. lineJoin: 'bevel'
  32714. }
  32715. ));
  32716. if (stackedOnSeries) {
  32717. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  32718. }
  32719. polygon.setShape({
  32720. smooth: smooth,
  32721. stackedOnSmooth: stackedOnSmooth,
  32722. smoothMonotone: seriesModel.get('smoothMonotone'),
  32723. connectNulls: seriesModel.get('connectNulls')
  32724. });
  32725. }
  32726. this._data = data;
  32727. // Save the coordinate system for transition animation when data changed
  32728. this._coordSys = coordSys;
  32729. this._stackedOnPoints = stackedOnPoints;
  32730. this._points = points;
  32731. this._step = step;
  32732. this._valueOrigin = valueOrigin;
  32733. },
  32734. dispose: function () {},
  32735. highlight: function (seriesModel, ecModel, api, payload) {
  32736. var data = seriesModel.getData();
  32737. var dataIndex = queryDataIndex(data, payload);
  32738. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  32739. var symbol = data.getItemGraphicEl(dataIndex);
  32740. if (!symbol) {
  32741. // Create a temporary symbol if it is not exists
  32742. var pt = data.getItemLayout(dataIndex);
  32743. if (!pt) {
  32744. // Null data
  32745. return;
  32746. }
  32747. symbol = new SymbolClz$1(data, dataIndex);
  32748. symbol.position = pt;
  32749. symbol.setZ(
  32750. seriesModel.get('zlevel'),
  32751. seriesModel.get('z')
  32752. );
  32753. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  32754. symbol.__temp = true;
  32755. data.setItemGraphicEl(dataIndex, symbol);
  32756. // Stop scale animation
  32757. symbol.stopSymbolAnimation(true);
  32758. this.group.add(symbol);
  32759. }
  32760. symbol.highlight();
  32761. }
  32762. else {
  32763. // Highlight whole series
  32764. Chart.prototype.highlight.call(
  32765. this, seriesModel, ecModel, api, payload
  32766. );
  32767. }
  32768. },
  32769. downplay: function (seriesModel, ecModel, api, payload) {
  32770. var data = seriesModel.getData();
  32771. var dataIndex = queryDataIndex(data, payload);
  32772. if (dataIndex != null && dataIndex >= 0) {
  32773. var symbol = data.getItemGraphicEl(dataIndex);
  32774. if (symbol) {
  32775. if (symbol.__temp) {
  32776. data.setItemGraphicEl(dataIndex, null);
  32777. this.group.remove(symbol);
  32778. }
  32779. else {
  32780. symbol.downplay();
  32781. }
  32782. }
  32783. }
  32784. else {
  32785. // FIXME
  32786. // can not downplay completely.
  32787. // Downplay whole series
  32788. Chart.prototype.downplay.call(
  32789. this, seriesModel, ecModel, api, payload
  32790. );
  32791. }
  32792. },
  32793. /**
  32794. * @param {module:zrender/container/Group} group
  32795. * @param {Array.<Array.<number>>} points
  32796. * @private
  32797. */
  32798. _newPolyline: function (points) {
  32799. var polyline = this._polyline;
  32800. // Remove previous created polyline
  32801. if (polyline) {
  32802. this._lineGroup.remove(polyline);
  32803. }
  32804. polyline = new Polyline$1({
  32805. shape: {
  32806. points: points
  32807. },
  32808. silent: true,
  32809. z2: 10
  32810. });
  32811. this._lineGroup.add(polyline);
  32812. this._polyline = polyline;
  32813. return polyline;
  32814. },
  32815. /**
  32816. * @param {module:zrender/container/Group} group
  32817. * @param {Array.<Array.<number>>} stackedOnPoints
  32818. * @param {Array.<Array.<number>>} points
  32819. * @private
  32820. */
  32821. _newPolygon: function (points, stackedOnPoints) {
  32822. var polygon = this._polygon;
  32823. // Remove previous created polygon
  32824. if (polygon) {
  32825. this._lineGroup.remove(polygon);
  32826. }
  32827. polygon = new Polygon$1({
  32828. shape: {
  32829. points: points,
  32830. stackedOnPoints: stackedOnPoints
  32831. },
  32832. silent: true
  32833. });
  32834. this._lineGroup.add(polygon);
  32835. this._polygon = polygon;
  32836. return polygon;
  32837. },
  32838. /**
  32839. * @private
  32840. */
  32841. // FIXME Two value axis
  32842. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  32843. var polyline = this._polyline;
  32844. var polygon = this._polygon;
  32845. var seriesModel = data.hostModel;
  32846. var diff = lineAnimationDiff(
  32847. this._data, data,
  32848. this._stackedOnPoints, stackedOnPoints,
  32849. this._coordSys, coordSys,
  32850. this._valueOrigin, valueOrigin
  32851. );
  32852. var current = diff.current;
  32853. var stackedOnCurrent = diff.stackedOnCurrent;
  32854. var next = diff.next;
  32855. var stackedOnNext = diff.stackedOnNext;
  32856. if (step) {
  32857. // TODO If stacked series is not step
  32858. current = turnPointsIntoStep(diff.current, coordSys, step);
  32859. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  32860. next = turnPointsIntoStep(diff.next, coordSys, step);
  32861. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  32862. }
  32863. // `diff.current` is subset of `current` (which should be ensured by
  32864. // turnPointsIntoStep), so points in `__points` can be updated when
  32865. // points in `current` are update during animation.
  32866. polyline.shape.__points = diff.current;
  32867. polyline.shape.points = current;
  32868. updateProps(polyline, {
  32869. shape: {
  32870. points: next
  32871. }
  32872. }, seriesModel);
  32873. if (polygon) {
  32874. polygon.setShape({
  32875. points: current,
  32876. stackedOnPoints: stackedOnCurrent
  32877. });
  32878. updateProps(polygon, {
  32879. shape: {
  32880. points: next,
  32881. stackedOnPoints: stackedOnNext
  32882. }
  32883. }, seriesModel);
  32884. }
  32885. var updatedDataInfo = [];
  32886. var diffStatus = diff.status;
  32887. for (var i = 0; i < diffStatus.length; i++) {
  32888. var cmd = diffStatus[i].cmd;
  32889. if (cmd === '=') {
  32890. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  32891. if (el) {
  32892. updatedDataInfo.push({
  32893. el: el,
  32894. ptIdx: i // Index of points
  32895. });
  32896. }
  32897. }
  32898. }
  32899. if (polyline.animators && polyline.animators.length) {
  32900. polyline.animators[0].during(function () {
  32901. for (var i = 0; i < updatedDataInfo.length; i++) {
  32902. var el = updatedDataInfo[i].el;
  32903. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  32904. }
  32905. });
  32906. }
  32907. },
  32908. remove: function (ecModel) {
  32909. var group = this.group;
  32910. var oldData = this._data;
  32911. this._lineGroup.removeAll();
  32912. this._symbolDraw.remove(true);
  32913. // Remove temporary created elements when highlighting
  32914. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  32915. if (el.__temp) {
  32916. group.remove(el);
  32917. oldData.setItemGraphicEl(idx, null);
  32918. }
  32919. });
  32920. this._polyline
  32921. = this._polygon
  32922. = this._coordSys
  32923. = this._points
  32924. = this._stackedOnPoints
  32925. = this._data = null;
  32926. }
  32927. });
  32928. /*
  32929. * Licensed to the Apache Software Foundation (ASF) under one
  32930. * or more contributor license agreements. See the NOTICE file
  32931. * distributed with this work for additional information
  32932. * regarding copyright ownership. The ASF licenses this file
  32933. * to you under the Apache License, Version 2.0 (the
  32934. * "License"); you may not use this file except in compliance
  32935. * with the License. You may obtain a copy of the License at
  32936. *
  32937. * http://www.apache.org/licenses/LICENSE-2.0
  32938. *
  32939. * Unless required by applicable law or agreed to in writing,
  32940. * software distributed under the License is distributed on an
  32941. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32942. * KIND, either express or implied. See the License for the
  32943. * specific language governing permissions and limitations
  32944. * under the License.
  32945. */
  32946. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  32947. // Encoding visual for all series include which is filtered for legend drawing
  32948. return {
  32949. seriesType: seriesType,
  32950. // For legend.
  32951. performRawSeries: true,
  32952. reset: function (seriesModel, ecModel, api) {
  32953. var data = seriesModel.getData();
  32954. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  32955. var symbolSize = seriesModel.get('symbolSize');
  32956. var keepAspect = seriesModel.get('symbolKeepAspect');
  32957. data.setVisual({
  32958. legendSymbol: legendSymbol || symbolType,
  32959. symbol: symbolType,
  32960. symbolSize: symbolSize,
  32961. symbolKeepAspect: keepAspect
  32962. });
  32963. // Only visible series has each data be visual encoded
  32964. if (ecModel.isSeriesFiltered(seriesModel)) {
  32965. return;
  32966. }
  32967. var hasCallback = typeof symbolSize === 'function';
  32968. function dataEach(data, idx) {
  32969. if (typeof symbolSize === 'function') {
  32970. var rawValue = seriesModel.getRawValue(idx);
  32971. // FIXME
  32972. var params = seriesModel.getDataParams(idx);
  32973. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  32974. }
  32975. if (data.hasItemOption) {
  32976. var itemModel = data.getItemModel(idx);
  32977. var itemSymbolType = itemModel.getShallow('symbol', true);
  32978. var itemSymbolSize = itemModel.getShallow('symbolSize',
  32979. true);
  32980. var itemSymbolKeepAspect
  32981. = itemModel.getShallow('symbolKeepAspect', true);
  32982. // If has item symbol
  32983. if (itemSymbolType != null) {
  32984. data.setItemVisual(idx, 'symbol', itemSymbolType);
  32985. }
  32986. if (itemSymbolSize != null) {
  32987. // PENDING Transform symbolSize ?
  32988. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  32989. }
  32990. if (itemSymbolKeepAspect != null) {
  32991. data.setItemVisual(idx, 'symbolKeepAspect',
  32992. itemSymbolKeepAspect);
  32993. }
  32994. }
  32995. }
  32996. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  32997. }
  32998. };
  32999. };
  33000. /*
  33001. * Licensed to the Apache Software Foundation (ASF) under one
  33002. * or more contributor license agreements. See the NOTICE file
  33003. * distributed with this work for additional information
  33004. * regarding copyright ownership. The ASF licenses this file
  33005. * to you under the Apache License, Version 2.0 (the
  33006. * "License"); you may not use this file except in compliance
  33007. * with the License. You may obtain a copy of the License at
  33008. *
  33009. * http://www.apache.org/licenses/LICENSE-2.0
  33010. *
  33011. * Unless required by applicable law or agreed to in writing,
  33012. * software distributed under the License is distributed on an
  33013. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33014. * KIND, either express or implied. See the License for the
  33015. * specific language governing permissions and limitations
  33016. * under the License.
  33017. */
  33018. /* global Float32Array */
  33019. var pointsLayout = function (seriesType) {
  33020. return {
  33021. seriesType: seriesType,
  33022. plan: createRenderPlanner(),
  33023. reset: function (seriesModel) {
  33024. var data = seriesModel.getData();
  33025. var coordSys = seriesModel.coordinateSystem;
  33026. var pipelineContext = seriesModel.pipelineContext;
  33027. var isLargeRender = pipelineContext.large;
  33028. if (!coordSys) {
  33029. return;
  33030. }
  33031. var dims = map(coordSys.dimensions, function (dim) {
  33032. return data.mapDimension(dim);
  33033. }).slice(0, 2);
  33034. var dimLen = dims.length;
  33035. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  33036. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  33037. dims[0] = stackResultDim;
  33038. }
  33039. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  33040. dims[1] = stackResultDim;
  33041. }
  33042. function progress(params, data) {
  33043. var segCount = params.end - params.start;
  33044. var points = isLargeRender && new Float32Array(segCount * dimLen);
  33045. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  33046. var point;
  33047. if (dimLen === 1) {
  33048. var x = data.get(dims[0], i);
  33049. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  33050. }
  33051. else {
  33052. var x = tmpIn[0] = data.get(dims[0], i);
  33053. var y = tmpIn[1] = data.get(dims[1], i);
  33054. // Also {Array.<number>}, not undefined to avoid if...else... statement
  33055. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  33056. }
  33057. if (isLargeRender) {
  33058. points[offset++] = point ? point[0] : NaN;
  33059. points[offset++] = point ? point[1] : NaN;
  33060. }
  33061. else {
  33062. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  33063. }
  33064. }
  33065. isLargeRender && data.setLayout('symbolPoints', points);
  33066. }
  33067. return dimLen && {progress: progress};
  33068. }
  33069. };
  33070. };
  33071. /*
  33072. * Licensed to the Apache Software Foundation (ASF) under one
  33073. * or more contributor license agreements. See the NOTICE file
  33074. * distributed with this work for additional information
  33075. * regarding copyright ownership. The ASF licenses this file
  33076. * to you under the Apache License, Version 2.0 (the
  33077. * "License"); you may not use this file except in compliance
  33078. * with the License. You may obtain a copy of the License at
  33079. *
  33080. * http://www.apache.org/licenses/LICENSE-2.0
  33081. *
  33082. * Unless required by applicable law or agreed to in writing,
  33083. * software distributed under the License is distributed on an
  33084. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33085. * KIND, either express or implied. See the License for the
  33086. * specific language governing permissions and limitations
  33087. * under the License.
  33088. */
  33089. var samplers = {
  33090. average: function (frame) {
  33091. var sum = 0;
  33092. var count = 0;
  33093. for (var i = 0; i < frame.length; i++) {
  33094. if (!isNaN(frame[i])) {
  33095. sum += frame[i];
  33096. count++;
  33097. }
  33098. }
  33099. // Return NaN if count is 0
  33100. return count === 0 ? NaN : sum / count;
  33101. },
  33102. sum: function (frame) {
  33103. var sum = 0;
  33104. for (var i = 0; i < frame.length; i++) {
  33105. // Ignore NaN
  33106. sum += frame[i] || 0;
  33107. }
  33108. return sum;
  33109. },
  33110. max: function (frame) {
  33111. var max = -Infinity;
  33112. for (var i = 0; i < frame.length; i++) {
  33113. frame[i] > max && (max = frame[i]);
  33114. }
  33115. // NaN will cause illegal axis extent.
  33116. return isFinite(max) ? max : NaN;
  33117. },
  33118. min: function (frame) {
  33119. var min = Infinity;
  33120. for (var i = 0; i < frame.length; i++) {
  33121. frame[i] < min && (min = frame[i]);
  33122. }
  33123. // NaN will cause illegal axis extent.
  33124. return isFinite(min) ? min : NaN;
  33125. },
  33126. // TODO
  33127. // Median
  33128. nearest: function (frame) {
  33129. return frame[0];
  33130. }
  33131. };
  33132. var indexSampler = function (frame, value) {
  33133. return Math.round(frame.length / 2);
  33134. };
  33135. var dataSample = function (seriesType) {
  33136. return {
  33137. seriesType: seriesType,
  33138. modifyOutputEnd: true,
  33139. reset: function (seriesModel, ecModel, api) {
  33140. var data = seriesModel.getData();
  33141. var sampling = seriesModel.get('sampling');
  33142. var coordSys = seriesModel.coordinateSystem;
  33143. // Only cartesian2d support down sampling
  33144. if (coordSys.type === 'cartesian2d' && sampling) {
  33145. var baseAxis = coordSys.getBaseAxis();
  33146. var valueAxis = coordSys.getOtherAxis(baseAxis);
  33147. var extent = baseAxis.getExtent();
  33148. // Coordinste system has been resized
  33149. var size = extent[1] - extent[0];
  33150. var rate = Math.round(data.count() / size);
  33151. if (rate > 1) {
  33152. var sampler;
  33153. if (typeof sampling === 'string') {
  33154. sampler = samplers[sampling];
  33155. }
  33156. else if (typeof sampling === 'function') {
  33157. sampler = sampling;
  33158. }
  33159. if (sampler) {
  33160. // Only support sample the first dim mapped from value axis.
  33161. seriesModel.setData(data.downSample(
  33162. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  33163. ));
  33164. }
  33165. }
  33166. }
  33167. }
  33168. };
  33169. };
  33170. /*
  33171. * Licensed to the Apache Software Foundation (ASF) under one
  33172. * or more contributor license agreements. See the NOTICE file
  33173. * distributed with this work for additional information
  33174. * regarding copyright ownership. The ASF licenses this file
  33175. * to you under the Apache License, Version 2.0 (the
  33176. * "License"); you may not use this file except in compliance
  33177. * with the License. You may obtain a copy of the License at
  33178. *
  33179. * http://www.apache.org/licenses/LICENSE-2.0
  33180. *
  33181. * Unless required by applicable law or agreed to in writing,
  33182. * software distributed under the License is distributed on an
  33183. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33184. * KIND, either express or implied. See the License for the
  33185. * specific language governing permissions and limitations
  33186. * under the License.
  33187. */
  33188. /**
  33189. * Cartesian coordinate system
  33190. * @module echarts/coord/Cartesian
  33191. *
  33192. */
  33193. function dimAxisMapper(dim) {
  33194. return this._axes[dim];
  33195. }
  33196. /**
  33197. * @alias module:echarts/coord/Cartesian
  33198. * @constructor
  33199. */
  33200. var Cartesian = function (name) {
  33201. this._axes = {};
  33202. this._dimList = [];
  33203. /**
  33204. * @type {string}
  33205. */
  33206. this.name = name || '';
  33207. };
  33208. Cartesian.prototype = {
  33209. constructor: Cartesian,
  33210. type: 'cartesian',
  33211. /**
  33212. * Get axis
  33213. * @param {number|string} dim
  33214. * @return {module:echarts/coord/Cartesian~Axis}
  33215. */
  33216. getAxis: function (dim) {
  33217. return this._axes[dim];
  33218. },
  33219. /**
  33220. * Get axes list
  33221. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  33222. */
  33223. getAxes: function () {
  33224. return map(this._dimList, dimAxisMapper, this);
  33225. },
  33226. /**
  33227. * Get axes list by given scale type
  33228. */
  33229. getAxesByScale: function (scaleType) {
  33230. scaleType = scaleType.toLowerCase();
  33231. return filter(
  33232. this.getAxes(),
  33233. function (axis) {
  33234. return axis.scale.type === scaleType;
  33235. }
  33236. );
  33237. },
  33238. /**
  33239. * Add axis
  33240. * @param {module:echarts/coord/Cartesian.Axis}
  33241. */
  33242. addAxis: function (axis) {
  33243. var dim = axis.dim;
  33244. this._axes[dim] = axis;
  33245. this._dimList.push(dim);
  33246. },
  33247. /**
  33248. * Convert data to coord in nd space
  33249. * @param {Array.<number>|Object.<string, number>} val
  33250. * @return {Array.<number>|Object.<string, number>}
  33251. */
  33252. dataToCoord: function (val) {
  33253. return this._dataCoordConvert(val, 'dataToCoord');
  33254. },
  33255. /**
  33256. * Convert coord in nd space to data
  33257. * @param {Array.<number>|Object.<string, number>} val
  33258. * @return {Array.<number>|Object.<string, number>}
  33259. */
  33260. coordToData: function (val) {
  33261. return this._dataCoordConvert(val, 'coordToData');
  33262. },
  33263. _dataCoordConvert: function (input, method) {
  33264. var dimList = this._dimList;
  33265. var output = input instanceof Array ? [] : {};
  33266. for (var i = 0; i < dimList.length; i++) {
  33267. var dim = dimList[i];
  33268. var axis = this._axes[dim];
  33269. output[dim] = axis[method](input[dim]);
  33270. }
  33271. return output;
  33272. }
  33273. };
  33274. /*
  33275. * Licensed to the Apache Software Foundation (ASF) under one
  33276. * or more contributor license agreements. See the NOTICE file
  33277. * distributed with this work for additional information
  33278. * regarding copyright ownership. The ASF licenses this file
  33279. * to you under the Apache License, Version 2.0 (the
  33280. * "License"); you may not use this file except in compliance
  33281. * with the License. You may obtain a copy of the License at
  33282. *
  33283. * http://www.apache.org/licenses/LICENSE-2.0
  33284. *
  33285. * Unless required by applicable law or agreed to in writing,
  33286. * software distributed under the License is distributed on an
  33287. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33288. * KIND, either express or implied. See the License for the
  33289. * specific language governing permissions and limitations
  33290. * under the License.
  33291. */
  33292. function Cartesian2D(name) {
  33293. Cartesian.call(this, name);
  33294. }
  33295. Cartesian2D.prototype = {
  33296. constructor: Cartesian2D,
  33297. type: 'cartesian2d',
  33298. /**
  33299. * @type {Array.<string>}
  33300. * @readOnly
  33301. */
  33302. dimensions: ['x', 'y'],
  33303. /**
  33304. * Base axis will be used on stacking.
  33305. *
  33306. * @return {module:echarts/coord/cartesian/Axis2D}
  33307. */
  33308. getBaseAxis: function () {
  33309. return this.getAxesByScale('ordinal')[0]
  33310. || this.getAxesByScale('time')[0]
  33311. || this.getAxis('x');
  33312. },
  33313. /**
  33314. * If contain point
  33315. * @param {Array.<number>} point
  33316. * @return {boolean}
  33317. */
  33318. containPoint: function (point) {
  33319. var axisX = this.getAxis('x');
  33320. var axisY = this.getAxis('y');
  33321. return axisX.contain(axisX.toLocalCoord(point[0]))
  33322. && axisY.contain(axisY.toLocalCoord(point[1]));
  33323. },
  33324. /**
  33325. * If contain data
  33326. * @param {Array.<number>} data
  33327. * @return {boolean}
  33328. */
  33329. containData: function (data) {
  33330. return this.getAxis('x').containData(data[0])
  33331. && this.getAxis('y').containData(data[1]);
  33332. },
  33333. /**
  33334. * @param {Array.<number>} data
  33335. * @param {Array.<number>} out
  33336. * @return {Array.<number>}
  33337. */
  33338. dataToPoint: function (data, reserved, out) {
  33339. var xAxis = this.getAxis('x');
  33340. var yAxis = this.getAxis('y');
  33341. out = out || [];
  33342. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  33343. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  33344. return out;
  33345. },
  33346. /**
  33347. * @param {Array.<number>} data
  33348. * @param {Array.<number>} out
  33349. * @return {Array.<number>}
  33350. */
  33351. clampData: function (data, out) {
  33352. var xScale = this.getAxis('x').scale;
  33353. var yScale = this.getAxis('y').scale;
  33354. var xAxisExtent = xScale.getExtent();
  33355. var yAxisExtent = yScale.getExtent();
  33356. var x = xScale.parse(data[0]);
  33357. var y = yScale.parse(data[1]);
  33358. out = out || [];
  33359. out[0] = Math.min(
  33360. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  33361. Math.max(xAxisExtent[0], xAxisExtent[1])
  33362. );
  33363. out[1] = Math.min(
  33364. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  33365. Math.max(yAxisExtent[0], yAxisExtent[1])
  33366. );
  33367. return out;
  33368. },
  33369. /**
  33370. * @param {Array.<number>} point
  33371. * @param {Array.<number>} out
  33372. * @return {Array.<number>}
  33373. */
  33374. pointToData: function (point, out) {
  33375. var xAxis = this.getAxis('x');
  33376. var yAxis = this.getAxis('y');
  33377. out = out || [];
  33378. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  33379. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  33380. return out;
  33381. },
  33382. /**
  33383. * Get other axis
  33384. * @param {module:echarts/coord/cartesian/Axis2D} axis
  33385. */
  33386. getOtherAxis: function (axis) {
  33387. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  33388. }
  33389. };
  33390. inherits(Cartesian2D, Cartesian);
  33391. /*
  33392. * Licensed to the Apache Software Foundation (ASF) under one
  33393. * or more contributor license agreements. See the NOTICE file
  33394. * distributed with this work for additional information
  33395. * regarding copyright ownership. The ASF licenses this file
  33396. * to you under the Apache License, Version 2.0 (the
  33397. * "License"); you may not use this file except in compliance
  33398. * with the License. You may obtain a copy of the License at
  33399. *
  33400. * http://www.apache.org/licenses/LICENSE-2.0
  33401. *
  33402. * Unless required by applicable law or agreed to in writing,
  33403. * software distributed under the License is distributed on an
  33404. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33405. * KIND, either express or implied. See the License for the
  33406. * specific language governing permissions and limitations
  33407. * under the License.
  33408. */
  33409. /**
  33410. * Extend axis 2d
  33411. * @constructor module:echarts/coord/cartesian/Axis2D
  33412. * @extends {module:echarts/coord/cartesian/Axis}
  33413. * @param {string} dim
  33414. * @param {*} scale
  33415. * @param {Array.<number>} coordExtent
  33416. * @param {string} axisType
  33417. * @param {string} position
  33418. */
  33419. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  33420. Axis.call(this, dim, scale, coordExtent);
  33421. /**
  33422. * Axis type
  33423. * - 'category'
  33424. * - 'value'
  33425. * - 'time'
  33426. * - 'log'
  33427. * @type {string}
  33428. */
  33429. this.type = axisType || 'value';
  33430. /**
  33431. * Axis position
  33432. * - 'top'
  33433. * - 'bottom'
  33434. * - 'left'
  33435. * - 'right'
  33436. */
  33437. this.position = position || 'bottom';
  33438. };
  33439. Axis2D.prototype = {
  33440. constructor: Axis2D,
  33441. /**
  33442. * Index of axis, can be used as key
  33443. */
  33444. index: 0,
  33445. /**
  33446. * Implemented in <module:echarts/coord/cartesian/Grid>.
  33447. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  33448. * If not on zero of other axis, return null/undefined.
  33449. * If no axes, return an empty array.
  33450. */
  33451. getAxesOnZeroOf: null,
  33452. /**
  33453. * Axis model
  33454. * @param {module:echarts/coord/cartesian/AxisModel}
  33455. */
  33456. model: null,
  33457. isHorizontal: function () {
  33458. var position = this.position;
  33459. return position === 'top' || position === 'bottom';
  33460. },
  33461. /**
  33462. * Each item cooresponds to this.getExtent(), which
  33463. * means globalExtent[0] may greater than globalExtent[1],
  33464. * unless `asc` is input.
  33465. *
  33466. * @param {boolean} [asc]
  33467. * @return {Array.<number>}
  33468. */
  33469. getGlobalExtent: function (asc) {
  33470. var ret = this.getExtent();
  33471. ret[0] = this.toGlobalCoord(ret[0]);
  33472. ret[1] = this.toGlobalCoord(ret[1]);
  33473. asc && ret[0] > ret[1] && ret.reverse();
  33474. return ret;
  33475. },
  33476. getOtherAxis: function () {
  33477. this.grid.getOtherAxis();
  33478. },
  33479. /**
  33480. * @override
  33481. */
  33482. pointToData: function (point, clamp) {
  33483. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  33484. },
  33485. /**
  33486. * Transform global coord to local coord,
  33487. * i.e. var localCoord = axis.toLocalCoord(80);
  33488. * designate by module:echarts/coord/cartesian/Grid.
  33489. * @type {Function}
  33490. */
  33491. toLocalCoord: null,
  33492. /**
  33493. * Transform global coord to local coord,
  33494. * i.e. var globalCoord = axis.toLocalCoord(40);
  33495. * designate by module:echarts/coord/cartesian/Grid.
  33496. * @type {Function}
  33497. */
  33498. toGlobalCoord: null
  33499. };
  33500. inherits(Axis2D, Axis);
  33501. /*
  33502. * Licensed to the Apache Software Foundation (ASF) under one
  33503. * or more contributor license agreements. See the NOTICE file
  33504. * distributed with this work for additional information
  33505. * regarding copyright ownership. The ASF licenses this file
  33506. * to you under the Apache License, Version 2.0 (the
  33507. * "License"); you may not use this file except in compliance
  33508. * with the License. You may obtain a copy of the License at
  33509. *
  33510. * http://www.apache.org/licenses/LICENSE-2.0
  33511. *
  33512. * Unless required by applicable law or agreed to in writing,
  33513. * software distributed under the License is distributed on an
  33514. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33515. * KIND, either express or implied. See the License for the
  33516. * specific language governing permissions and limitations
  33517. * under the License.
  33518. */
  33519. var defaultOption = {
  33520. show: true,
  33521. zlevel: 0,
  33522. z: 0,
  33523. // Inverse the axis.
  33524. inverse: false,
  33525. // Axis name displayed.
  33526. name: '',
  33527. // 'start' | 'middle' | 'end'
  33528. nameLocation: 'end',
  33529. // By degree. By defualt auto rotate by nameLocation.
  33530. nameRotate: null,
  33531. nameTruncate: {
  33532. maxWidth: null,
  33533. ellipsis: '...',
  33534. placeholder: '.'
  33535. },
  33536. // Use global text style by default.
  33537. nameTextStyle: {},
  33538. // The gap between axisName and axisLine.
  33539. nameGap: 15,
  33540. // Default `false` to support tooltip.
  33541. silent: false,
  33542. // Default `false` to avoid legacy user event listener fail.
  33543. triggerEvent: false,
  33544. tooltip: {
  33545. show: false
  33546. },
  33547. axisPointer: {},
  33548. axisLine: {
  33549. show: true,
  33550. onZero: true,
  33551. onZeroAxisIndex: null,
  33552. lineStyle: {
  33553. color: '#333',
  33554. width: 1,
  33555. type: 'solid'
  33556. },
  33557. // The arrow at both ends the the axis.
  33558. symbol: ['none', 'none'],
  33559. symbolSize: [10, 15]
  33560. },
  33561. axisTick: {
  33562. show: true,
  33563. // Whether axisTick is inside the grid or outside the grid.
  33564. inside: false,
  33565. // The length of axisTick.
  33566. length: 5,
  33567. lineStyle: {
  33568. width: 1
  33569. }
  33570. },
  33571. axisLabel: {
  33572. show: true,
  33573. // Whether axisLabel is inside the grid or outside the grid.
  33574. inside: false,
  33575. rotate: 0,
  33576. // true | false | null/undefined (auto)
  33577. showMinLabel: null,
  33578. // true | false | null/undefined (auto)
  33579. showMaxLabel: null,
  33580. margin: 8,
  33581. // formatter: null,
  33582. fontSize: 12
  33583. },
  33584. splitLine: {
  33585. show: true,
  33586. lineStyle: {
  33587. color: ['#ccc'],
  33588. width: 1,
  33589. type: 'solid'
  33590. }
  33591. },
  33592. splitArea: {
  33593. show: false,
  33594. areaStyle: {
  33595. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  33596. }
  33597. }
  33598. };
  33599. var axisDefault = {};
  33600. axisDefault.categoryAxis = merge({
  33601. // The gap at both ends of the axis. For categoryAxis, boolean.
  33602. boundaryGap: true,
  33603. // Set false to faster category collection.
  33604. // Only usefull in the case like: category is
  33605. // ['2012-01-01', '2012-01-02', ...], where the input
  33606. // data has been ensured not duplicate and is large data.
  33607. // null means "auto":
  33608. // if axis.data provided, do not deduplication,
  33609. // else do deduplication.
  33610. deduplication: null,
  33611. // splitArea: {
  33612. // show: false
  33613. // },
  33614. splitLine: {
  33615. show: false
  33616. },
  33617. axisTick: {
  33618. // If tick is align with label when boundaryGap is true
  33619. alignWithLabel: false,
  33620. interval: 'auto'
  33621. },
  33622. axisLabel: {
  33623. interval: 'auto'
  33624. }
  33625. }, defaultOption);
  33626. axisDefault.valueAxis = merge({
  33627. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  33628. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  33629. boundaryGap: [0, 0],
  33630. // TODO
  33631. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  33632. // Min value of the axis. can be:
  33633. // + a number
  33634. // + 'dataMin': use the min value in data.
  33635. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  33636. // min: null,
  33637. // Max value of the axis. can be:
  33638. // + a number
  33639. // + 'dataMax': use the max value in data.
  33640. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  33641. // max: null,
  33642. // Readonly prop, specifies start value of the range when using data zoom.
  33643. // rangeStart: null
  33644. // Readonly prop, specifies end value of the range when using data zoom.
  33645. // rangeEnd: null
  33646. // Optional value can be:
  33647. // + `false`: always include value 0.
  33648. // + `true`: the extent do not consider value 0.
  33649. // scale: false,
  33650. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  33651. splitNumber: 5
  33652. // Interval specifies the span of the ticks is mandatorily.
  33653. // interval: null
  33654. // Specify min interval when auto calculate tick interval.
  33655. // minInterval: null
  33656. // Specify max interval when auto calculate tick interval.
  33657. // maxInterval: null
  33658. }, defaultOption);
  33659. axisDefault.timeAxis = defaults({
  33660. scale: true,
  33661. min: 'dataMin',
  33662. max: 'dataMax'
  33663. }, axisDefault.valueAxis);
  33664. axisDefault.logAxis = defaults({
  33665. scale: true,
  33666. logBase: 10
  33667. }, axisDefault.valueAxis);
  33668. /*
  33669. * Licensed to the Apache Software Foundation (ASF) under one
  33670. * or more contributor license agreements. See the NOTICE file
  33671. * distributed with this work for additional information
  33672. * regarding copyright ownership. The ASF licenses this file
  33673. * to you under the Apache License, Version 2.0 (the
  33674. * "License"); you may not use this file except in compliance
  33675. * with the License. You may obtain a copy of the License at
  33676. *
  33677. * http://www.apache.org/licenses/LICENSE-2.0
  33678. *
  33679. * Unless required by applicable law or agreed to in writing,
  33680. * software distributed under the License is distributed on an
  33681. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33682. * KIND, either express or implied. See the License for the
  33683. * specific language governing permissions and limitations
  33684. * under the License.
  33685. */
  33686. // FIXME axisType is fixed ?
  33687. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  33688. /**
  33689. * Generate sub axis model class
  33690. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  33691. * @param {module:echarts/model/Component} BaseAxisModelClass
  33692. * @param {Function} axisTypeDefaulter
  33693. * @param {Object} [extraDefaultOption]
  33694. */
  33695. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  33696. each$1(AXIS_TYPES, function (axisType) {
  33697. BaseAxisModelClass.extend({
  33698. /**
  33699. * @readOnly
  33700. */
  33701. type: axisName + 'Axis.' + axisType,
  33702. mergeDefaultAndTheme: function (option, ecModel) {
  33703. var layoutMode = this.layoutMode;
  33704. var inputPositionParams = layoutMode
  33705. ? getLayoutParams(option) : {};
  33706. var themeModel = ecModel.getTheme();
  33707. merge(option, themeModel.get(axisType + 'Axis'));
  33708. merge(option, this.getDefaultOption());
  33709. option.type = axisTypeDefaulter(axisName, option);
  33710. if (layoutMode) {
  33711. mergeLayoutParam(option, inputPositionParams, layoutMode);
  33712. }
  33713. },
  33714. /**
  33715. * @override
  33716. */
  33717. optionUpdated: function () {
  33718. var thisOption = this.option;
  33719. if (thisOption.type === 'category') {
  33720. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  33721. }
  33722. },
  33723. /**
  33724. * Should not be called before all of 'getInitailData' finished.
  33725. * Because categories are collected during initializing data.
  33726. */
  33727. getCategories: function (rawData) {
  33728. var option = this.option;
  33729. // FIXME
  33730. // warning if called before all of 'getInitailData' finished.
  33731. if (option.type === 'category') {
  33732. if (rawData) {
  33733. return option.data;
  33734. }
  33735. return this.__ordinalMeta.categories;
  33736. }
  33737. },
  33738. getOrdinalMeta: function () {
  33739. return this.__ordinalMeta;
  33740. },
  33741. defaultOption: mergeAll(
  33742. [
  33743. {},
  33744. axisDefault[axisType + 'Axis'],
  33745. extraDefaultOption
  33746. ],
  33747. true
  33748. )
  33749. });
  33750. });
  33751. ComponentModel.registerSubTypeDefaulter(
  33752. axisName + 'Axis',
  33753. curry(axisTypeDefaulter, axisName)
  33754. );
  33755. };
  33756. /*
  33757. * Licensed to the Apache Software Foundation (ASF) under one
  33758. * or more contributor license agreements. See the NOTICE file
  33759. * distributed with this work for additional information
  33760. * regarding copyright ownership. The ASF licenses this file
  33761. * to you under the Apache License, Version 2.0 (the
  33762. * "License"); you may not use this file except in compliance
  33763. * with the License. You may obtain a copy of the License at
  33764. *
  33765. * http://www.apache.org/licenses/LICENSE-2.0
  33766. *
  33767. * Unless required by applicable law or agreed to in writing,
  33768. * software distributed under the License is distributed on an
  33769. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33770. * KIND, either express or implied. See the License for the
  33771. * specific language governing permissions and limitations
  33772. * under the License.
  33773. */
  33774. var AxisModel = ComponentModel.extend({
  33775. type: 'cartesian2dAxis',
  33776. /**
  33777. * @type {module:echarts/coord/cartesian/Axis2D}
  33778. */
  33779. axis: null,
  33780. /**
  33781. * @override
  33782. */
  33783. init: function () {
  33784. AxisModel.superApply(this, 'init', arguments);
  33785. this.resetRange();
  33786. },
  33787. /**
  33788. * @override
  33789. */
  33790. mergeOption: function () {
  33791. AxisModel.superApply(this, 'mergeOption', arguments);
  33792. this.resetRange();
  33793. },
  33794. /**
  33795. * @override
  33796. */
  33797. restoreData: function () {
  33798. AxisModel.superApply(this, 'restoreData', arguments);
  33799. this.resetRange();
  33800. },
  33801. /**
  33802. * @override
  33803. * @return {module:echarts/model/Component}
  33804. */
  33805. getCoordSysModel: function () {
  33806. return this.ecModel.queryComponents({
  33807. mainType: 'grid',
  33808. index: this.option.gridIndex,
  33809. id: this.option.gridId
  33810. })[0];
  33811. }
  33812. });
  33813. function getAxisType(axisDim, option) {
  33814. // Default axis with data is category axis
  33815. return option.type || (option.data ? 'category' : 'value');
  33816. }
  33817. merge(AxisModel.prototype, axisModelCommonMixin);
  33818. var extraOption = {
  33819. // gridIndex: 0,
  33820. // gridId: '',
  33821. // Offset is for multiple axis on the same position
  33822. offset: 0
  33823. };
  33824. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  33825. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  33826. /*
  33827. * Licensed to the Apache Software Foundation (ASF) under one
  33828. * or more contributor license agreements. See the NOTICE file
  33829. * distributed with this work for additional information
  33830. * regarding copyright ownership. The ASF licenses this file
  33831. * to you under the Apache License, Version 2.0 (the
  33832. * "License"); you may not use this file except in compliance
  33833. * with the License. You may obtain a copy of the License at
  33834. *
  33835. * http://www.apache.org/licenses/LICENSE-2.0
  33836. *
  33837. * Unless required by applicable law or agreed to in writing,
  33838. * software distributed under the License is distributed on an
  33839. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33840. * KIND, either express or implied. See the License for the
  33841. * specific language governing permissions and limitations
  33842. * under the License.
  33843. */
  33844. // Grid 是在有直角坐标系的时候必须要存在的
  33845. // 所以这里也要被 Cartesian2D 依赖
  33846. ComponentModel.extend({
  33847. type: 'grid',
  33848. dependencies: ['xAxis', 'yAxis'],
  33849. layoutMode: 'box',
  33850. /**
  33851. * @type {module:echarts/coord/cartesian/Grid}
  33852. */
  33853. coordinateSystem: null,
  33854. defaultOption: {
  33855. show: false,
  33856. zlevel: 0,
  33857. z: 0,
  33858. left: '10%',
  33859. top: 60,
  33860. right: '10%',
  33861. bottom: 60,
  33862. // If grid size contain label
  33863. containLabel: false,
  33864. // width: {totalWidth} - left - right,
  33865. // height: {totalHeight} - top - bottom,
  33866. backgroundColor: 'rgba(0,0,0,0)',
  33867. borderWidth: 1,
  33868. borderColor: '#ccc'
  33869. }
  33870. });
  33871. /*
  33872. * Licensed to the Apache Software Foundation (ASF) under one
  33873. * or more contributor license agreements. See the NOTICE file
  33874. * distributed with this work for additional information
  33875. * regarding copyright ownership. The ASF licenses this file
  33876. * to you under the Apache License, Version 2.0 (the
  33877. * "License"); you may not use this file except in compliance
  33878. * with the License. You may obtain a copy of the License at
  33879. *
  33880. * http://www.apache.org/licenses/LICENSE-2.0
  33881. *
  33882. * Unless required by applicable law or agreed to in writing,
  33883. * software distributed under the License is distributed on an
  33884. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33885. * KIND, either express or implied. See the License for the
  33886. * specific language governing permissions and limitations
  33887. * under the License.
  33888. */
  33889. /**
  33890. * Grid is a region which contains at most 4 cartesian systems
  33891. *
  33892. * TODO Default cartesian
  33893. */
  33894. // Depends on GridModel, AxisModel, which performs preprocess.
  33895. /**
  33896. * Check if the axis is used in the specified grid
  33897. * @inner
  33898. */
  33899. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  33900. return axisModel.getCoordSysModel() === gridModel;
  33901. }
  33902. function Grid(gridModel, ecModel, api) {
  33903. /**
  33904. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  33905. * @private
  33906. */
  33907. this._coordsMap = {};
  33908. /**
  33909. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  33910. * @private
  33911. */
  33912. this._coordsList = [];
  33913. /**
  33914. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  33915. * @private
  33916. */
  33917. this._axesMap = {};
  33918. /**
  33919. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  33920. * @private
  33921. */
  33922. this._axesList = [];
  33923. this._initCartesian(gridModel, ecModel, api);
  33924. this.model = gridModel;
  33925. }
  33926. var gridProto = Grid.prototype;
  33927. gridProto.type = 'grid';
  33928. gridProto.axisPointerEnabled = true;
  33929. gridProto.getRect = function () {
  33930. return this._rect;
  33931. };
  33932. gridProto.update = function (ecModel, api) {
  33933. var axesMap = this._axesMap;
  33934. this._updateScale(ecModel, this.model);
  33935. each$1(axesMap.x, function (xAxis) {
  33936. niceScaleExtent(xAxis.scale, xAxis.model);
  33937. });
  33938. each$1(axesMap.y, function (yAxis) {
  33939. niceScaleExtent(yAxis.scale, yAxis.model);
  33940. });
  33941. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  33942. var onZeroRecords = {};
  33943. each$1(axesMap.x, function (xAxis) {
  33944. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  33945. });
  33946. each$1(axesMap.y, function (yAxis) {
  33947. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  33948. });
  33949. // Resize again if containLabel is enabled
  33950. // FIXME It may cause getting wrong grid size in data processing stage
  33951. this.resize(this.model, api);
  33952. };
  33953. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  33954. axis.getAxesOnZeroOf = function () {
  33955. // TODO: onZero of multiple axes.
  33956. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  33957. };
  33958. // onZero can not be enabled in these two situations:
  33959. // 1. When any other axis is a category axis.
  33960. // 2. When no axis is cross 0 point.
  33961. var otherAxes = axesMap[otherAxisDim];
  33962. var otherAxisOnZeroOf;
  33963. var axisModel = axis.model;
  33964. var onZero = axisModel.get('axisLine.onZero');
  33965. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  33966. if (!onZero) {
  33967. return;
  33968. }
  33969. // If target axis is specified.
  33970. if (onZeroAxisIndex != null) {
  33971. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  33972. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  33973. }
  33974. }
  33975. else {
  33976. // Find the first available other axis.
  33977. for (var idx in otherAxes) {
  33978. if (otherAxes.hasOwnProperty(idx)
  33979. && canOnZeroToAxis(otherAxes[idx])
  33980. // Consider that two Y axes on one value axis,
  33981. // if both onZero, the two Y axes overlap.
  33982. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  33983. ) {
  33984. otherAxisOnZeroOf = otherAxes[idx];
  33985. break;
  33986. }
  33987. }
  33988. }
  33989. if (otherAxisOnZeroOf) {
  33990. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  33991. }
  33992. function getOnZeroRecordKey(axis) {
  33993. return axis.dim + '_' + axis.index;
  33994. }
  33995. }
  33996. function canOnZeroToAxis(axis) {
  33997. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  33998. }
  33999. /**
  34000. * Resize the grid
  34001. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  34002. * @param {module:echarts/ExtensionAPI} api
  34003. */
  34004. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  34005. var gridRect = getLayoutRect(
  34006. gridModel.getBoxLayoutParams(), {
  34007. width: api.getWidth(),
  34008. height: api.getHeight()
  34009. });
  34010. this._rect = gridRect;
  34011. var axesList = this._axesList;
  34012. adjustAxes();
  34013. // Minus label size
  34014. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  34015. each$1(axesList, function (axis) {
  34016. if (!axis.model.get('axisLabel.inside')) {
  34017. var labelUnionRect = estimateLabelUnionRect(axis);
  34018. if (labelUnionRect) {
  34019. var dim = axis.isHorizontal() ? 'height' : 'width';
  34020. var margin = axis.model.get('axisLabel.margin');
  34021. gridRect[dim] -= labelUnionRect[dim] + margin;
  34022. if (axis.position === 'top') {
  34023. gridRect.y += labelUnionRect.height + margin;
  34024. }
  34025. else if (axis.position === 'left') {
  34026. gridRect.x += labelUnionRect.width + margin;
  34027. }
  34028. }
  34029. }
  34030. });
  34031. adjustAxes();
  34032. }
  34033. function adjustAxes() {
  34034. each$1(axesList, function (axis) {
  34035. var isHorizontal = axis.isHorizontal();
  34036. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  34037. var idx = axis.inverse ? 1 : 0;
  34038. axis.setExtent(extent[idx], extent[1 - idx]);
  34039. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  34040. });
  34041. }
  34042. };
  34043. /**
  34044. * @param {string} axisType
  34045. * @param {number} [axisIndex]
  34046. */
  34047. gridProto.getAxis = function (axisType, axisIndex) {
  34048. var axesMapOnDim = this._axesMap[axisType];
  34049. if (axesMapOnDim != null) {
  34050. if (axisIndex == null) {
  34051. // Find first axis
  34052. for (var name in axesMapOnDim) {
  34053. if (axesMapOnDim.hasOwnProperty(name)) {
  34054. return axesMapOnDim[name];
  34055. }
  34056. }
  34057. }
  34058. return axesMapOnDim[axisIndex];
  34059. }
  34060. };
  34061. /**
  34062. * @return {Array.<module:echarts/coord/Axis>}
  34063. */
  34064. gridProto.getAxes = function () {
  34065. return this._axesList.slice();
  34066. };
  34067. /**
  34068. * Usage:
  34069. * grid.getCartesian(xAxisIndex, yAxisIndex);
  34070. * grid.getCartesian(xAxisIndex);
  34071. * grid.getCartesian(null, yAxisIndex);
  34072. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  34073. *
  34074. * @param {number|Object} [xAxisIndex]
  34075. * @param {number} [yAxisIndex]
  34076. */
  34077. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  34078. if (xAxisIndex != null && yAxisIndex != null) {
  34079. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  34080. return this._coordsMap[key];
  34081. }
  34082. if (isObject$1(xAxisIndex)) {
  34083. yAxisIndex = xAxisIndex.yAxisIndex;
  34084. xAxisIndex = xAxisIndex.xAxisIndex;
  34085. }
  34086. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  34087. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  34088. if (coordList[i].getAxis('x').index === xAxisIndex
  34089. || coordList[i].getAxis('y').index === yAxisIndex
  34090. ) {
  34091. return coordList[i];
  34092. }
  34093. }
  34094. };
  34095. gridProto.getCartesians = function () {
  34096. return this._coordsList.slice();
  34097. };
  34098. /**
  34099. * @implements
  34100. * see {module:echarts/CoodinateSystem}
  34101. */
  34102. gridProto.convertToPixel = function (ecModel, finder, value) {
  34103. var target = this._findConvertTarget(ecModel, finder);
  34104. return target.cartesian
  34105. ? target.cartesian.dataToPoint(value)
  34106. : target.axis
  34107. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  34108. : null;
  34109. };
  34110. /**
  34111. * @implements
  34112. * see {module:echarts/CoodinateSystem}
  34113. */
  34114. gridProto.convertFromPixel = function (ecModel, finder, value) {
  34115. var target = this._findConvertTarget(ecModel, finder);
  34116. return target.cartesian
  34117. ? target.cartesian.pointToData(value)
  34118. : target.axis
  34119. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  34120. : null;
  34121. };
  34122. /**
  34123. * @inner
  34124. */
  34125. gridProto._findConvertTarget = function (ecModel, finder) {
  34126. var seriesModel = finder.seriesModel;
  34127. var xAxisModel = finder.xAxisModel
  34128. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  34129. var yAxisModel = finder.yAxisModel
  34130. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  34131. var gridModel = finder.gridModel;
  34132. var coordsList = this._coordsList;
  34133. var cartesian;
  34134. var axis;
  34135. if (seriesModel) {
  34136. cartesian = seriesModel.coordinateSystem;
  34137. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  34138. }
  34139. else if (xAxisModel && yAxisModel) {
  34140. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  34141. }
  34142. else if (xAxisModel) {
  34143. axis = this.getAxis('x', xAxisModel.componentIndex);
  34144. }
  34145. else if (yAxisModel) {
  34146. axis = this.getAxis('y', yAxisModel.componentIndex);
  34147. }
  34148. // Lowest priority.
  34149. else if (gridModel) {
  34150. var grid = gridModel.coordinateSystem;
  34151. if (grid === this) {
  34152. cartesian = this._coordsList[0];
  34153. }
  34154. }
  34155. return {cartesian: cartesian, axis: axis};
  34156. };
  34157. /**
  34158. * @implements
  34159. * see {module:echarts/CoodinateSystem}
  34160. */
  34161. gridProto.containPoint = function (point) {
  34162. var coord = this._coordsList[0];
  34163. if (coord) {
  34164. return coord.containPoint(point);
  34165. }
  34166. };
  34167. /**
  34168. * Initialize cartesian coordinate systems
  34169. * @private
  34170. */
  34171. gridProto._initCartesian = function (gridModel, ecModel, api) {
  34172. var axisPositionUsed = {
  34173. left: false,
  34174. right: false,
  34175. top: false,
  34176. bottom: false
  34177. };
  34178. var axesMap = {
  34179. x: {},
  34180. y: {}
  34181. };
  34182. var axesCount = {
  34183. x: 0,
  34184. y: 0
  34185. };
  34186. /// Create axis
  34187. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  34188. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  34189. if (!axesCount.x || !axesCount.y) {
  34190. // Roll back when there no either x or y axis
  34191. this._axesMap = {};
  34192. this._axesList = [];
  34193. return;
  34194. }
  34195. this._axesMap = axesMap;
  34196. /// Create cartesian2d
  34197. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  34198. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  34199. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  34200. var cartesian = new Cartesian2D(key);
  34201. cartesian.grid = this;
  34202. cartesian.model = gridModel;
  34203. this._coordsMap[key] = cartesian;
  34204. this._coordsList.push(cartesian);
  34205. cartesian.addAxis(xAxis);
  34206. cartesian.addAxis(yAxis);
  34207. }, this);
  34208. }, this);
  34209. function createAxisCreator(axisType) {
  34210. return function (axisModel, idx) {
  34211. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  34212. return;
  34213. }
  34214. var axisPosition = axisModel.get('position');
  34215. if (axisType === 'x') {
  34216. // Fix position
  34217. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  34218. // Default bottom of X
  34219. axisPosition = 'bottom';
  34220. if (axisPositionUsed[axisPosition]) {
  34221. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  34222. }
  34223. }
  34224. }
  34225. else {
  34226. // Fix position
  34227. if (axisPosition !== 'left' && axisPosition !== 'right') {
  34228. // Default left of Y
  34229. axisPosition = 'left';
  34230. if (axisPositionUsed[axisPosition]) {
  34231. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  34232. }
  34233. }
  34234. }
  34235. axisPositionUsed[axisPosition] = true;
  34236. var axis = new Axis2D(
  34237. axisType, createScaleByModel(axisModel),
  34238. [0, 0],
  34239. axisModel.get('type'),
  34240. axisPosition
  34241. );
  34242. var isCategory = axis.type === 'category';
  34243. axis.onBand = isCategory && axisModel.get('boundaryGap');
  34244. axis.inverse = axisModel.get('inverse');
  34245. // Inject axis into axisModel
  34246. axisModel.axis = axis;
  34247. // Inject axisModel into axis
  34248. axis.model = axisModel;
  34249. // Inject grid info axis
  34250. axis.grid = this;
  34251. // Index of axis, can be used as key
  34252. axis.index = idx;
  34253. this._axesList.push(axis);
  34254. axesMap[axisType][idx] = axis;
  34255. axesCount[axisType]++;
  34256. };
  34257. }
  34258. };
  34259. /**
  34260. * Update cartesian properties from series
  34261. * @param {module:echarts/model/Option} option
  34262. * @private
  34263. */
  34264. gridProto._updateScale = function (ecModel, gridModel) {
  34265. // Reset scale
  34266. each$1(this._axesList, function (axis) {
  34267. axis.scale.setExtent(Infinity, -Infinity);
  34268. });
  34269. ecModel.eachSeries(function (seriesModel) {
  34270. if (isCartesian2D(seriesModel)) {
  34271. var axesModels = findAxesModels(seriesModel, ecModel);
  34272. var xAxisModel = axesModels[0];
  34273. var yAxisModel = axesModels[1];
  34274. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  34275. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  34276. ) {
  34277. return;
  34278. }
  34279. var cartesian = this.getCartesian(
  34280. xAxisModel.componentIndex, yAxisModel.componentIndex
  34281. );
  34282. var data = seriesModel.getData();
  34283. var xAxis = cartesian.getAxis('x');
  34284. var yAxis = cartesian.getAxis('y');
  34285. if (data.type === 'list') {
  34286. unionExtent(data, xAxis, seriesModel);
  34287. unionExtent(data, yAxis, seriesModel);
  34288. }
  34289. }
  34290. }, this);
  34291. function unionExtent(data, axis, seriesModel) {
  34292. each$1(data.mapDimension(axis.dim, true), function (dim) {
  34293. axis.scale.unionExtentFromData(
  34294. // For example, the extent of the orginal dimension
  34295. // is [0.1, 0.5], the extent of the `stackResultDimension`
  34296. // is [7, 9], the final extent should not include [0.1, 0.5].
  34297. data, getStackedDimension(data, dim)
  34298. );
  34299. });
  34300. }
  34301. };
  34302. /**
  34303. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  34304. * @return {Object} {baseAxes: [], otherAxes: []}
  34305. */
  34306. gridProto.getTooltipAxes = function (dim) {
  34307. var baseAxes = [];
  34308. var otherAxes = [];
  34309. each$1(this.getCartesians(), function (cartesian) {
  34310. var baseAxis = (dim != null && dim !== 'auto')
  34311. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  34312. var otherAxis = cartesian.getOtherAxis(baseAxis);
  34313. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  34314. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  34315. });
  34316. return {baseAxes: baseAxes, otherAxes: otherAxes};
  34317. };
  34318. /**
  34319. * @inner
  34320. */
  34321. function updateAxisTransform(axis, coordBase) {
  34322. var axisExtent = axis.getExtent();
  34323. var axisExtentSum = axisExtent[0] + axisExtent[1];
  34324. // Fast transform
  34325. axis.toGlobalCoord = axis.dim === 'x'
  34326. ? function (coord) {
  34327. return coord + coordBase;
  34328. }
  34329. : function (coord) {
  34330. return axisExtentSum - coord + coordBase;
  34331. };
  34332. axis.toLocalCoord = axis.dim === 'x'
  34333. ? function (coord) {
  34334. return coord - coordBase;
  34335. }
  34336. : function (coord) {
  34337. return axisExtentSum - coord + coordBase;
  34338. };
  34339. }
  34340. var axesTypes = ['xAxis', 'yAxis'];
  34341. /**
  34342. * @inner
  34343. */
  34344. function findAxesModels(seriesModel, ecModel) {
  34345. return map(axesTypes, function (axisType) {
  34346. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  34347. if (__DEV__) {
  34348. if (!axisModel) {
  34349. throw new Error(axisType + ' "' + retrieve(
  34350. seriesModel.get(axisType + 'Index'),
  34351. seriesModel.get(axisType + 'Id'),
  34352. 0
  34353. ) + '" not found');
  34354. }
  34355. }
  34356. return axisModel;
  34357. });
  34358. }
  34359. /**
  34360. * @inner
  34361. */
  34362. function isCartesian2D(seriesModel) {
  34363. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  34364. }
  34365. Grid.create = function (ecModel, api) {
  34366. var grids = [];
  34367. ecModel.eachComponent('grid', function (gridModel, idx) {
  34368. var grid = new Grid(gridModel, ecModel, api);
  34369. grid.name = 'grid_' + idx;
  34370. // dataSampling requires axis extent, so resize
  34371. // should be performed in create stage.
  34372. grid.resize(gridModel, api, true);
  34373. gridModel.coordinateSystem = grid;
  34374. grids.push(grid);
  34375. });
  34376. // Inject the coordinateSystems into seriesModel
  34377. ecModel.eachSeries(function (seriesModel) {
  34378. if (!isCartesian2D(seriesModel)) {
  34379. return;
  34380. }
  34381. var axesModels = findAxesModels(seriesModel, ecModel);
  34382. var xAxisModel = axesModels[0];
  34383. var yAxisModel = axesModels[1];
  34384. var gridModel = xAxisModel.getCoordSysModel();
  34385. if (__DEV__) {
  34386. if (!gridModel) {
  34387. throw new Error(
  34388. 'Grid "' + retrieve(
  34389. xAxisModel.get('gridIndex'),
  34390. xAxisModel.get('gridId'),
  34391. 0
  34392. ) + '" not found'
  34393. );
  34394. }
  34395. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  34396. throw new Error('xAxis and yAxis must use the same grid');
  34397. }
  34398. }
  34399. var grid = gridModel.coordinateSystem;
  34400. seriesModel.coordinateSystem = grid.getCartesian(
  34401. xAxisModel.componentIndex, yAxisModel.componentIndex
  34402. );
  34403. });
  34404. return grids;
  34405. };
  34406. // For deciding which dimensions to use when creating list data
  34407. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  34408. CoordinateSystemManager.register('cartesian2d', Grid);
  34409. /*
  34410. * Licensed to the Apache Software Foundation (ASF) under one
  34411. * or more contributor license agreements. See the NOTICE file
  34412. * distributed with this work for additional information
  34413. * regarding copyright ownership. The ASF licenses this file
  34414. * to you under the Apache License, Version 2.0 (the
  34415. * "License"); you may not use this file except in compliance
  34416. * with the License. You may obtain a copy of the License at
  34417. *
  34418. * http://www.apache.org/licenses/LICENSE-2.0
  34419. *
  34420. * Unless required by applicable law or agreed to in writing,
  34421. * software distributed under the License is distributed on an
  34422. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34423. * KIND, either express or implied. See the License for the
  34424. * specific language governing permissions and limitations
  34425. * under the License.
  34426. */
  34427. var PI$2 = Math.PI;
  34428. function makeAxisEventDataBase(axisModel) {
  34429. var eventData = {
  34430. componentType: axisModel.mainType,
  34431. componentIndex: axisModel.componentIndex
  34432. };
  34433. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  34434. return eventData;
  34435. }
  34436. /**
  34437. * A final axis is translated and rotated from a "standard axis".
  34438. * So opt.position and opt.rotation is required.
  34439. *
  34440. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  34441. * for example: (0, 0) ------------> (0, 50)
  34442. *
  34443. * nameDirection or tickDirection or labelDirection is 1 means tick
  34444. * or label is below the standard axis, whereas is -1 means above
  34445. * the standard axis. labelOffset means offset between label and axis,
  34446. * which is useful when 'onZero', where axisLabel is in the grid and
  34447. * label in outside grid.
  34448. *
  34449. * Tips: like always,
  34450. * positive rotation represents anticlockwise, and negative rotation
  34451. * represents clockwise.
  34452. * The direction of position coordinate is the same as the direction
  34453. * of screen coordinate.
  34454. *
  34455. * Do not need to consider axis 'inverse', which is auto processed by
  34456. * axis extent.
  34457. *
  34458. * @param {module:zrender/container/Group} group
  34459. * @param {Object} axisModel
  34460. * @param {Object} opt Standard axis parameters.
  34461. * @param {Array.<number>} opt.position [x, y]
  34462. * @param {number} opt.rotation by radian
  34463. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  34464. * @param {number} [opt.tickDirection=1] 1 or -1
  34465. * @param {number} [opt.labelDirection=1] 1 or -1
  34466. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  34467. * @param {string} [opt.axisLabelShow] default get from axisModel.
  34468. * @param {string} [opt.axisName] default get from axisModel.
  34469. * @param {number} [opt.axisNameAvailableWidth]
  34470. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  34471. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  34472. * @param {number} [opt.nameTruncateMaxWidth]
  34473. */
  34474. var AxisBuilder = function (axisModel, opt) {
  34475. /**
  34476. * @readOnly
  34477. */
  34478. this.opt = opt;
  34479. /**
  34480. * @readOnly
  34481. */
  34482. this.axisModel = axisModel;
  34483. // Default value
  34484. defaults(
  34485. opt,
  34486. {
  34487. labelOffset: 0,
  34488. nameDirection: 1,
  34489. tickDirection: 1,
  34490. labelDirection: 1,
  34491. silent: true
  34492. }
  34493. );
  34494. /**
  34495. * @readOnly
  34496. */
  34497. this.group = new Group();
  34498. // FIXME Not use a seperate text group?
  34499. var dumbGroup = new Group({
  34500. position: opt.position.slice(),
  34501. rotation: opt.rotation
  34502. });
  34503. // this.group.add(dumbGroup);
  34504. // this._dumbGroup = dumbGroup;
  34505. dumbGroup.updateTransform();
  34506. this._transform = dumbGroup.transform;
  34507. this._dumbGroup = dumbGroup;
  34508. };
  34509. AxisBuilder.prototype = {
  34510. constructor: AxisBuilder,
  34511. hasBuilder: function (name) {
  34512. return !!builders[name];
  34513. },
  34514. add: function (name) {
  34515. builders[name].call(this);
  34516. },
  34517. getGroup: function () {
  34518. return this.group;
  34519. }
  34520. };
  34521. var builders = {
  34522. /**
  34523. * @private
  34524. */
  34525. axisLine: function () {
  34526. var opt = this.opt;
  34527. var axisModel = this.axisModel;
  34528. if (!axisModel.get('axisLine.show')) {
  34529. return;
  34530. }
  34531. var extent = this.axisModel.axis.getExtent();
  34532. var matrix = this._transform;
  34533. var pt1 = [extent[0], 0];
  34534. var pt2 = [extent[1], 0];
  34535. if (matrix) {
  34536. applyTransform(pt1, pt1, matrix);
  34537. applyTransform(pt2, pt2, matrix);
  34538. }
  34539. var lineStyle = extend(
  34540. {
  34541. lineCap: 'round'
  34542. },
  34543. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  34544. );
  34545. this.group.add(new Line(subPixelOptimizeLine({
  34546. // Id for animation
  34547. anid: 'line',
  34548. shape: {
  34549. x1: pt1[0],
  34550. y1: pt1[1],
  34551. x2: pt2[0],
  34552. y2: pt2[1]
  34553. },
  34554. style: lineStyle,
  34555. strokeContainThreshold: opt.strokeContainThreshold || 5,
  34556. silent: true,
  34557. z2: 1
  34558. })));
  34559. var arrows = axisModel.get('axisLine.symbol');
  34560. var arrowSize = axisModel.get('axisLine.symbolSize');
  34561. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  34562. if (typeof arrowOffset === 'number') {
  34563. arrowOffset = [arrowOffset, arrowOffset];
  34564. }
  34565. if (arrows != null) {
  34566. if (typeof arrows === 'string') {
  34567. // Use the same arrow for start and end point
  34568. arrows = [arrows, arrows];
  34569. }
  34570. if (typeof arrowSize === 'string'
  34571. || typeof arrowSize === 'number'
  34572. ) {
  34573. // Use the same size for width and height
  34574. arrowSize = [arrowSize, arrowSize];
  34575. }
  34576. var symbolWidth = arrowSize[0];
  34577. var symbolHeight = arrowSize[1];
  34578. each$1([{
  34579. rotate: opt.rotation + Math.PI / 2,
  34580. offset: arrowOffset[0],
  34581. r: 0
  34582. }, {
  34583. rotate: opt.rotation - Math.PI / 2,
  34584. offset: arrowOffset[1],
  34585. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  34586. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  34587. }], function (point, index) {
  34588. if (arrows[index] !== 'none' && arrows[index] != null) {
  34589. var symbol = createSymbol(
  34590. arrows[index],
  34591. -symbolWidth / 2,
  34592. -symbolHeight / 2,
  34593. symbolWidth,
  34594. symbolHeight,
  34595. lineStyle.stroke,
  34596. true
  34597. );
  34598. // Calculate arrow position with offset
  34599. var r = point.r + point.offset;
  34600. var pos = [
  34601. pt1[0] + r * Math.cos(opt.rotation),
  34602. pt1[1] - r * Math.sin(opt.rotation)
  34603. ];
  34604. symbol.attr({
  34605. rotation: point.rotate,
  34606. position: pos,
  34607. silent: true,
  34608. z2: 11
  34609. });
  34610. this.group.add(symbol);
  34611. }
  34612. }, this);
  34613. }
  34614. },
  34615. /**
  34616. * @private
  34617. */
  34618. axisTickLabel: function () {
  34619. var axisModel = this.axisModel;
  34620. var opt = this.opt;
  34621. var tickEls = buildAxisTick(this, axisModel, opt);
  34622. var labelEls = buildAxisLabel(this, axisModel, opt);
  34623. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  34624. },
  34625. /**
  34626. * @private
  34627. */
  34628. axisName: function () {
  34629. var opt = this.opt;
  34630. var axisModel = this.axisModel;
  34631. var name = retrieve(opt.axisName, axisModel.get('name'));
  34632. if (!name) {
  34633. return;
  34634. }
  34635. var nameLocation = axisModel.get('nameLocation');
  34636. var nameDirection = opt.nameDirection;
  34637. var textStyleModel = axisModel.getModel('nameTextStyle');
  34638. var gap = axisModel.get('nameGap') || 0;
  34639. var extent = this.axisModel.axis.getExtent();
  34640. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  34641. var pos = [
  34642. nameLocation === 'start'
  34643. ? extent[0] - gapSignal * gap
  34644. : nameLocation === 'end'
  34645. ? extent[1] + gapSignal * gap
  34646. : (extent[0] + extent[1]) / 2, // 'middle'
  34647. // Reuse labelOffset.
  34648. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  34649. ];
  34650. var labelLayout;
  34651. var nameRotation = axisModel.get('nameRotate');
  34652. if (nameRotation != null) {
  34653. nameRotation = nameRotation * PI$2 / 180; // To radian.
  34654. }
  34655. var axisNameAvailableWidth;
  34656. if (isNameLocationCenter(nameLocation)) {
  34657. labelLayout = innerTextLayout(
  34658. opt.rotation,
  34659. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  34660. nameDirection
  34661. );
  34662. }
  34663. else {
  34664. labelLayout = endTextLayout(
  34665. opt, nameLocation, nameRotation || 0, extent
  34666. );
  34667. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  34668. if (axisNameAvailableWidth != null) {
  34669. axisNameAvailableWidth = Math.abs(
  34670. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  34671. );
  34672. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  34673. }
  34674. }
  34675. var textFont = textStyleModel.getFont();
  34676. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  34677. var ellipsis = truncateOpt.ellipsis;
  34678. var maxWidth = retrieve(
  34679. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  34680. );
  34681. // FIXME
  34682. // truncate rich text? (consider performance)
  34683. var truncatedText = (ellipsis != null && maxWidth != null)
  34684. ? truncateText$1(
  34685. name, maxWidth, textFont, ellipsis,
  34686. {minChar: 2, placeholder: truncateOpt.placeholder}
  34687. )
  34688. : name;
  34689. var tooltipOpt = axisModel.get('tooltip', true);
  34690. var mainType = axisModel.mainType;
  34691. var formatterParams = {
  34692. componentType: mainType,
  34693. name: name,
  34694. $vars: ['name']
  34695. };
  34696. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  34697. var textEl = new Text({
  34698. // Id for animation
  34699. anid: 'name',
  34700. __fullText: name,
  34701. __truncatedText: truncatedText,
  34702. position: pos,
  34703. rotation: labelLayout.rotation,
  34704. silent: isSilent(axisModel),
  34705. z2: 1,
  34706. tooltip: (tooltipOpt && tooltipOpt.show)
  34707. ? extend({
  34708. content: name,
  34709. formatter: function () {
  34710. return name;
  34711. },
  34712. formatterParams: formatterParams
  34713. }, tooltipOpt)
  34714. : null
  34715. });
  34716. setTextStyle(textEl.style, textStyleModel, {
  34717. text: truncatedText,
  34718. textFont: textFont,
  34719. textFill: textStyleModel.getTextColor()
  34720. || axisModel.get('axisLine.lineStyle.color'),
  34721. textAlign: labelLayout.textAlign,
  34722. textVerticalAlign: labelLayout.textVerticalAlign
  34723. });
  34724. if (axisModel.get('triggerEvent')) {
  34725. textEl.eventData = makeAxisEventDataBase(axisModel);
  34726. textEl.eventData.targetType = 'axisName';
  34727. textEl.eventData.name = name;
  34728. }
  34729. // FIXME
  34730. this._dumbGroup.add(textEl);
  34731. textEl.updateTransform();
  34732. this.group.add(textEl);
  34733. textEl.decomposeTransform();
  34734. }
  34735. };
  34736. /**
  34737. * @public
  34738. * @static
  34739. * @param {Object} opt
  34740. * @param {number} axisRotation in radian
  34741. * @param {number} textRotation in radian
  34742. * @param {number} direction
  34743. * @return {Object} {
  34744. * rotation, // according to axis
  34745. * textAlign,
  34746. * textVerticalAlign
  34747. * }
  34748. */
  34749. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  34750. var rotationDiff = remRadian(textRotation - axisRotation);
  34751. var textAlign;
  34752. var textVerticalAlign;
  34753. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  34754. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  34755. textAlign = 'center';
  34756. }
  34757. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  34758. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  34759. textAlign = 'center';
  34760. }
  34761. else {
  34762. textVerticalAlign = 'middle';
  34763. if (rotationDiff > 0 && rotationDiff < PI$2) {
  34764. textAlign = direction > 0 ? 'right' : 'left';
  34765. }
  34766. else {
  34767. textAlign = direction > 0 ? 'left' : 'right';
  34768. }
  34769. }
  34770. return {
  34771. rotation: rotationDiff,
  34772. textAlign: textAlign,
  34773. textVerticalAlign: textVerticalAlign
  34774. };
  34775. };
  34776. function endTextLayout(opt, textPosition, textRotate, extent) {
  34777. var rotationDiff = remRadian(textRotate - opt.rotation);
  34778. var textAlign;
  34779. var textVerticalAlign;
  34780. var inverse = extent[0] > extent[1];
  34781. var onLeft = (textPosition === 'start' && !inverse)
  34782. || (textPosition !== 'start' && inverse);
  34783. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  34784. textVerticalAlign = onLeft ? 'bottom' : 'top';
  34785. textAlign = 'center';
  34786. }
  34787. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  34788. textVerticalAlign = onLeft ? 'top' : 'bottom';
  34789. textAlign = 'center';
  34790. }
  34791. else {
  34792. textVerticalAlign = 'middle';
  34793. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  34794. textAlign = onLeft ? 'left' : 'right';
  34795. }
  34796. else {
  34797. textAlign = onLeft ? 'right' : 'left';
  34798. }
  34799. }
  34800. return {
  34801. rotation: rotationDiff,
  34802. textAlign: textAlign,
  34803. textVerticalAlign: textVerticalAlign
  34804. };
  34805. }
  34806. function isSilent(axisModel) {
  34807. var tooltipOpt = axisModel.get('tooltip');
  34808. return axisModel.get('silent')
  34809. // Consider mouse cursor, add these restrictions.
  34810. || !(
  34811. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  34812. );
  34813. }
  34814. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  34815. if (shouldShowAllLabels(axisModel.axis)) {
  34816. return;
  34817. }
  34818. // If min or max are user set, we need to check
  34819. // If the tick on min(max) are overlap on their neighbour tick
  34820. // If they are overlapped, we need to hide the min(max) tick label
  34821. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  34822. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  34823. // FIXME
  34824. // Have not consider onBand yet, where tick els is more than label els.
  34825. labelEls = labelEls || [];
  34826. tickEls = tickEls || [];
  34827. var firstLabel = labelEls[0];
  34828. var nextLabel = labelEls[1];
  34829. var lastLabel = labelEls[labelEls.length - 1];
  34830. var prevLabel = labelEls[labelEls.length - 2];
  34831. var firstTick = tickEls[0];
  34832. var nextTick = tickEls[1];
  34833. var lastTick = tickEls[tickEls.length - 1];
  34834. var prevTick = tickEls[tickEls.length - 2];
  34835. if (showMinLabel === false) {
  34836. ignoreEl(firstLabel);
  34837. ignoreEl(firstTick);
  34838. }
  34839. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  34840. if (showMinLabel) {
  34841. ignoreEl(nextLabel);
  34842. ignoreEl(nextTick);
  34843. }
  34844. else {
  34845. ignoreEl(firstLabel);
  34846. ignoreEl(firstTick);
  34847. }
  34848. }
  34849. if (showMaxLabel === false) {
  34850. ignoreEl(lastLabel);
  34851. ignoreEl(lastTick);
  34852. }
  34853. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  34854. if (showMaxLabel) {
  34855. ignoreEl(prevLabel);
  34856. ignoreEl(prevTick);
  34857. }
  34858. else {
  34859. ignoreEl(lastLabel);
  34860. ignoreEl(lastTick);
  34861. }
  34862. }
  34863. }
  34864. function ignoreEl(el) {
  34865. el && (el.ignore = true);
  34866. }
  34867. function isTwoLabelOverlapped(current, next, labelLayout) {
  34868. // current and next has the same rotation.
  34869. var firstRect = current && current.getBoundingRect().clone();
  34870. var nextRect = next && next.getBoundingRect().clone();
  34871. if (!firstRect || !nextRect) {
  34872. return;
  34873. }
  34874. // When checking intersect of two rotated labels, we use mRotationBack
  34875. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  34876. var mRotationBack = identity([]);
  34877. rotate(mRotationBack, mRotationBack, -current.rotation);
  34878. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  34879. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  34880. return firstRect.intersect(nextRect);
  34881. }
  34882. function isNameLocationCenter(nameLocation) {
  34883. return nameLocation === 'middle' || nameLocation === 'center';
  34884. }
  34885. function buildAxisTick(axisBuilder, axisModel, opt) {
  34886. var axis = axisModel.axis;
  34887. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  34888. return;
  34889. }
  34890. var tickModel = axisModel.getModel('axisTick');
  34891. var lineStyleModel = tickModel.getModel('lineStyle');
  34892. var tickLen = tickModel.get('length');
  34893. var ticksCoords = axis.getTicksCoords();
  34894. var pt1 = [];
  34895. var pt2 = [];
  34896. var matrix = axisBuilder._transform;
  34897. var tickEls = [];
  34898. for (var i = 0; i < ticksCoords.length; i++) {
  34899. var tickCoord = ticksCoords[i].coord;
  34900. pt1[0] = tickCoord;
  34901. pt1[1] = 0;
  34902. pt2[0] = tickCoord;
  34903. pt2[1] = opt.tickDirection * tickLen;
  34904. if (matrix) {
  34905. applyTransform(pt1, pt1, matrix);
  34906. applyTransform(pt2, pt2, matrix);
  34907. }
  34908. // Tick line, Not use group transform to have better line draw
  34909. var tickEl = new Line(subPixelOptimizeLine({
  34910. // Id for animation
  34911. anid: 'tick_' + ticksCoords[i].tickValue,
  34912. shape: {
  34913. x1: pt1[0],
  34914. y1: pt1[1],
  34915. x2: pt2[0],
  34916. y2: pt2[1]
  34917. },
  34918. style: defaults(
  34919. lineStyleModel.getLineStyle(),
  34920. {
  34921. stroke: axisModel.get('axisLine.lineStyle.color')
  34922. }
  34923. ),
  34924. z2: 2,
  34925. silent: true
  34926. }));
  34927. axisBuilder.group.add(tickEl);
  34928. tickEls.push(tickEl);
  34929. }
  34930. return tickEls;
  34931. }
  34932. function buildAxisLabel(axisBuilder, axisModel, opt) {
  34933. var axis = axisModel.axis;
  34934. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  34935. if (!show || axis.scale.isBlank()) {
  34936. return;
  34937. }
  34938. var labelModel = axisModel.getModel('axisLabel');
  34939. var labelMargin = labelModel.get('margin');
  34940. var labels = axis.getViewLabels();
  34941. // Special label rotate.
  34942. var labelRotation = (
  34943. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  34944. ) * PI$2 / 180;
  34945. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  34946. var rawCategoryData = axisModel.getCategories(true);
  34947. var labelEls = [];
  34948. var silent = isSilent(axisModel);
  34949. var triggerEvent = axisModel.get('triggerEvent');
  34950. each$1(labels, function (labelItem, index) {
  34951. var tickValue = labelItem.tickValue;
  34952. var formattedLabel = labelItem.formattedLabel;
  34953. var rawLabel = labelItem.rawLabel;
  34954. var itemLabelModel = labelModel;
  34955. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  34956. itemLabelModel = new Model(
  34957. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  34958. );
  34959. }
  34960. var textColor = itemLabelModel.getTextColor()
  34961. || axisModel.get('axisLine.lineStyle.color');
  34962. var tickCoord = axis.dataToCoord(tickValue);
  34963. var pos = [
  34964. tickCoord,
  34965. opt.labelOffset + opt.labelDirection * labelMargin
  34966. ];
  34967. var textEl = new Text({
  34968. // Id for animation
  34969. anid: 'label_' + tickValue,
  34970. position: pos,
  34971. rotation: labelLayout.rotation,
  34972. silent: silent,
  34973. z2: 10
  34974. });
  34975. setTextStyle(textEl.style, itemLabelModel, {
  34976. text: formattedLabel,
  34977. textAlign: itemLabelModel.getShallow('align', true)
  34978. || labelLayout.textAlign,
  34979. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  34980. || itemLabelModel.getShallow('baseline', true)
  34981. || labelLayout.textVerticalAlign,
  34982. textFill: typeof textColor === 'function'
  34983. ? textColor(
  34984. // (1) In category axis with data zoom, tick is not the original
  34985. // index of axis.data. So tick should not be exposed to user
  34986. // in category axis.
  34987. // (2) Compatible with previous version, which always use formatted label as
  34988. // input. But in interval scale the formatted label is like '223,445', which
  34989. // maked user repalce ','. So we modify it to return original val but remain
  34990. // it as 'string' to avoid error in replacing.
  34991. axis.type === 'category'
  34992. ? rawLabel
  34993. : axis.type === 'value'
  34994. ? tickValue + ''
  34995. : tickValue,
  34996. index
  34997. )
  34998. : textColor
  34999. });
  35000. // Pack data for mouse event
  35001. if (triggerEvent) {
  35002. textEl.eventData = makeAxisEventDataBase(axisModel);
  35003. textEl.eventData.targetType = 'axisLabel';
  35004. textEl.eventData.value = rawLabel;
  35005. }
  35006. // FIXME
  35007. axisBuilder._dumbGroup.add(textEl);
  35008. textEl.updateTransform();
  35009. labelEls.push(textEl);
  35010. axisBuilder.group.add(textEl);
  35011. textEl.decomposeTransform();
  35012. });
  35013. return labelEls;
  35014. }
  35015. /*
  35016. * Licensed to the Apache Software Foundation (ASF) under one
  35017. * or more contributor license agreements. See the NOTICE file
  35018. * distributed with this work for additional information
  35019. * regarding copyright ownership. The ASF licenses this file
  35020. * to you under the Apache License, Version 2.0 (the
  35021. * "License"); you may not use this file except in compliance
  35022. * with the License. You may obtain a copy of the License at
  35023. *
  35024. * http://www.apache.org/licenses/LICENSE-2.0
  35025. *
  35026. * Unless required by applicable law or agreed to in writing,
  35027. * software distributed under the License is distributed on an
  35028. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35029. * KIND, either express or implied. See the License for the
  35030. * specific language governing permissions and limitations
  35031. * under the License.
  35032. */
  35033. var each$6 = each$1;
  35034. var curry$1 = curry;
  35035. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  35036. // allAxesInfo should be updated when setOption performed.
  35037. function collect(ecModel, api) {
  35038. var result = {
  35039. /**
  35040. * key: makeKey(axis.model)
  35041. * value: {
  35042. * axis,
  35043. * coordSys,
  35044. * axisPointerModel,
  35045. * triggerTooltip,
  35046. * involveSeries,
  35047. * snap,
  35048. * seriesModels,
  35049. * seriesDataCount
  35050. * }
  35051. */
  35052. axesInfo: {},
  35053. seriesInvolved: false,
  35054. /**
  35055. * key: makeKey(coordSys.model)
  35056. * value: Object: key makeKey(axis.model), value: axisInfo
  35057. */
  35058. coordSysAxesInfo: {},
  35059. coordSysMap: {}
  35060. };
  35061. collectAxesInfo(result, ecModel, api);
  35062. // Check seriesInvolved for performance, in case too many series in some chart.
  35063. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  35064. return result;
  35065. }
  35066. function collectAxesInfo(result, ecModel, api) {
  35067. var globalTooltipModel = ecModel.getComponent('tooltip');
  35068. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  35069. // links can only be set on global.
  35070. var linksOption = globalAxisPointerModel.get('link', true) || [];
  35071. var linkGroups = [];
  35072. // Collect axes info.
  35073. each$6(api.getCoordinateSystems(), function (coordSys) {
  35074. // Some coordinate system do not support axes, like geo.
  35075. if (!coordSys.axisPointerEnabled) {
  35076. return;
  35077. }
  35078. var coordSysKey = makeKey(coordSys.model);
  35079. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  35080. result.coordSysMap[coordSysKey] = coordSys;
  35081. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  35082. // for user. So we enable seting tooltip on coordSys model.
  35083. var coordSysModel = coordSys.model;
  35084. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  35085. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  35086. // If axis tooltip used, choose tooltip axis for each coordSys.
  35087. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  35088. if (coordSys.getTooltipAxes
  35089. && globalTooltipModel
  35090. // If tooltip.showContent is set as false, tooltip will not
  35091. // show but axisPointer will show as normal.
  35092. && baseTooltipModel.get('show')
  35093. ) {
  35094. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  35095. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  35096. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  35097. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  35098. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  35099. if (triggerAxis || cross) {
  35100. each$6(tooltipAxes.baseAxes, curry$1(
  35101. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  35102. ));
  35103. }
  35104. if (cross) {
  35105. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  35106. }
  35107. }
  35108. // fromTooltip: true | false | 'cross'
  35109. // triggerTooltip: true | false | null
  35110. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  35111. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  35112. var axisPointerShow = axisPointerModel.get('show');
  35113. if (!axisPointerShow || (
  35114. axisPointerShow === 'auto'
  35115. && !fromTooltip
  35116. && !isHandleTrigger(axisPointerModel)
  35117. )) {
  35118. return;
  35119. }
  35120. if (triggerTooltip == null) {
  35121. triggerTooltip = axisPointerModel.get('triggerTooltip');
  35122. }
  35123. axisPointerModel = fromTooltip
  35124. ? makeAxisPointerModel(
  35125. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  35126. fromTooltip, triggerTooltip
  35127. )
  35128. : axisPointerModel;
  35129. var snap = axisPointerModel.get('snap');
  35130. var key = makeKey(axis.model);
  35131. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  35132. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  35133. var axisInfo = result.axesInfo[key] = {
  35134. key: key,
  35135. axis: axis,
  35136. coordSys: coordSys,
  35137. axisPointerModel: axisPointerModel,
  35138. triggerTooltip: triggerTooltip,
  35139. involveSeries: involveSeries,
  35140. snap: snap,
  35141. useHandle: isHandleTrigger(axisPointerModel),
  35142. seriesModels: []
  35143. };
  35144. axesInfoInCoordSys[key] = axisInfo;
  35145. result.seriesInvolved |= involveSeries;
  35146. var groupIndex = getLinkGroupIndex(linksOption, axis);
  35147. if (groupIndex != null) {
  35148. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  35149. linkGroup.axesInfo[key] = axisInfo;
  35150. linkGroup.mapper = linksOption[groupIndex].mapper;
  35151. axisInfo.linkGroup = linkGroup;
  35152. }
  35153. }
  35154. });
  35155. }
  35156. function makeAxisPointerModel(
  35157. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  35158. ) {
  35159. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  35160. var volatileOption = {};
  35161. each$6(
  35162. [
  35163. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  35164. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  35165. ],
  35166. function (field) {
  35167. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  35168. }
  35169. );
  35170. // category axis do not auto snap, otherwise some tick that do not
  35171. // has value can not be hovered. value/time/log axis default snap if
  35172. // triggered from tooltip and trigger tooltip.
  35173. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  35174. // Compatibel with previous behavior, tooltip axis do not show label by default.
  35175. // Only these properties can be overrided from tooltip to axisPointer.
  35176. if (tooltipAxisPointerModel.get('type') === 'cross') {
  35177. volatileOption.type = 'line';
  35178. }
  35179. var labelOption = volatileOption.label || (volatileOption.label = {});
  35180. // Follow the convention, do not show label when triggered by tooltip by default.
  35181. labelOption.show == null && (labelOption.show = false);
  35182. if (fromTooltip === 'cross') {
  35183. // When 'cross', both axes show labels.
  35184. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  35185. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  35186. // If triggerTooltip, this is a base axis, which should better not use cross style
  35187. // (cross style is dashed by default)
  35188. if (!triggerTooltip) {
  35189. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  35190. crossStyle && defaults(labelOption, crossStyle.textStyle);
  35191. }
  35192. }
  35193. return axis.model.getModel(
  35194. 'axisPointer',
  35195. new Model(volatileOption, globalAxisPointerModel, ecModel)
  35196. );
  35197. }
  35198. function collectSeriesInfo(result, ecModel) {
  35199. // Prepare data for axis trigger
  35200. ecModel.eachSeries(function (seriesModel) {
  35201. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  35202. var coordSys = seriesModel.coordinateSystem;
  35203. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  35204. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  35205. if (!coordSys
  35206. || seriesTooltipTrigger === 'none'
  35207. || seriesTooltipTrigger === false
  35208. || seriesTooltipTrigger === 'item'
  35209. || seriesTooltipShow === false
  35210. || seriesModel.get('axisPointer.show', true) === false
  35211. ) {
  35212. return;
  35213. }
  35214. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  35215. var axis = axisInfo.axis;
  35216. if (coordSys.getAxis(axis.dim) === axis) {
  35217. axisInfo.seriesModels.push(seriesModel);
  35218. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  35219. axisInfo.seriesDataCount += seriesModel.getData().count();
  35220. }
  35221. });
  35222. }, this);
  35223. }
  35224. /**
  35225. * For example:
  35226. * {
  35227. * axisPointer: {
  35228. * links: [{
  35229. * xAxisIndex: [2, 4],
  35230. * yAxisIndex: 'all'
  35231. * }, {
  35232. * xAxisId: ['a5', 'a7'],
  35233. * xAxisName: 'xxx'
  35234. * }]
  35235. * }
  35236. * }
  35237. */
  35238. function getLinkGroupIndex(linksOption, axis) {
  35239. var axisModel = axis.model;
  35240. var dim = axis.dim;
  35241. for (var i = 0; i < linksOption.length; i++) {
  35242. var linkOption = linksOption[i] || {};
  35243. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  35244. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  35245. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  35246. ) {
  35247. return i;
  35248. }
  35249. }
  35250. }
  35251. function checkPropInLink(linkPropValue, axisPropValue) {
  35252. return linkPropValue === 'all'
  35253. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  35254. || linkPropValue === axisPropValue;
  35255. }
  35256. function fixValue(axisModel) {
  35257. var axisInfo = getAxisInfo(axisModel);
  35258. if (!axisInfo) {
  35259. return;
  35260. }
  35261. var axisPointerModel = axisInfo.axisPointerModel;
  35262. var scale = axisInfo.axis.scale;
  35263. var option = axisPointerModel.option;
  35264. var status = axisPointerModel.get('status');
  35265. var value = axisPointerModel.get('value');
  35266. // Parse init value for category and time axis.
  35267. if (value != null) {
  35268. value = scale.parse(value);
  35269. }
  35270. var useHandle = isHandleTrigger(axisPointerModel);
  35271. // If `handle` used, `axisPointer` will always be displayed, so value
  35272. // and status should be initialized.
  35273. if (status == null) {
  35274. option.status = useHandle ? 'show' : 'hide';
  35275. }
  35276. var extent = scale.getExtent().slice();
  35277. extent[0] > extent[1] && extent.reverse();
  35278. if (// Pick a value on axis when initializing.
  35279. value == null
  35280. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  35281. // where we should re-pick a value to keep `handle` displaying normally.
  35282. || value > extent[1]
  35283. ) {
  35284. // Make handle displayed on the end of the axis when init, which looks better.
  35285. value = extent[1];
  35286. }
  35287. if (value < extent[0]) {
  35288. value = extent[0];
  35289. }
  35290. option.value = value;
  35291. if (useHandle) {
  35292. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  35293. }
  35294. }
  35295. function getAxisInfo(axisModel) {
  35296. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  35297. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  35298. }
  35299. function getAxisPointerModel(axisModel) {
  35300. var axisInfo = getAxisInfo(axisModel);
  35301. return axisInfo && axisInfo.axisPointerModel;
  35302. }
  35303. function isHandleTrigger(axisPointerModel) {
  35304. return !!axisPointerModel.get('handle.show');
  35305. }
  35306. /**
  35307. * @param {module:echarts/model/Model} model
  35308. * @return {string} unique key
  35309. */
  35310. function makeKey(model) {
  35311. return model.type + '||' + model.id;
  35312. }
  35313. /*
  35314. * Licensed to the Apache Software Foundation (ASF) under one
  35315. * or more contributor license agreements. See the NOTICE file
  35316. * distributed with this work for additional information
  35317. * regarding copyright ownership. The ASF licenses this file
  35318. * to you under the Apache License, Version 2.0 (the
  35319. * "License"); you may not use this file except in compliance
  35320. * with the License. You may obtain a copy of the License at
  35321. *
  35322. * http://www.apache.org/licenses/LICENSE-2.0
  35323. *
  35324. * Unless required by applicable law or agreed to in writing,
  35325. * software distributed under the License is distributed on an
  35326. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35327. * KIND, either express or implied. See the License for the
  35328. * specific language governing permissions and limitations
  35329. * under the License.
  35330. */
  35331. /**
  35332. * Base class of AxisView.
  35333. */
  35334. var AxisView = extendComponentView({
  35335. type: 'axis',
  35336. /**
  35337. * @private
  35338. */
  35339. _axisPointer: null,
  35340. /**
  35341. * @protected
  35342. * @type {string}
  35343. */
  35344. axisPointerClass: null,
  35345. /**
  35346. * @override
  35347. */
  35348. render: function (axisModel, ecModel, api, payload) {
  35349. // FIXME
  35350. // This process should proformed after coordinate systems updated
  35351. // (axis scale updated), and should be performed each time update.
  35352. // So put it here temporarily, although it is not appropriate to
  35353. // put a model-writing procedure in `view`.
  35354. this.axisPointerClass && fixValue(axisModel);
  35355. AxisView.superApply(this, 'render', arguments);
  35356. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  35357. },
  35358. /**
  35359. * Action handler.
  35360. * @public
  35361. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35362. * @param {module:echarts/model/Global} ecModel
  35363. * @param {module:echarts/ExtensionAPI} api
  35364. * @param {Object} payload
  35365. */
  35366. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  35367. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  35368. },
  35369. /**
  35370. * @override
  35371. */
  35372. remove: function (ecModel, api) {
  35373. var axisPointer = this._axisPointer;
  35374. axisPointer && axisPointer.remove(api);
  35375. AxisView.superApply(this, 'remove', arguments);
  35376. },
  35377. /**
  35378. * @override
  35379. */
  35380. dispose: function (ecModel, api) {
  35381. disposeAxisPointer(this, api);
  35382. AxisView.superApply(this, 'dispose', arguments);
  35383. }
  35384. });
  35385. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  35386. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  35387. if (!Clazz) {
  35388. return;
  35389. }
  35390. var axisPointerModel = getAxisPointerModel(axisModel);
  35391. axisPointerModel
  35392. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  35393. .render(axisModel, axisPointerModel, api, forceRender)
  35394. : disposeAxisPointer(axisView, api);
  35395. }
  35396. function disposeAxisPointer(axisView, ecModel, api) {
  35397. var axisPointer = axisView._axisPointer;
  35398. axisPointer && axisPointer.dispose(ecModel, api);
  35399. axisView._axisPointer = null;
  35400. }
  35401. var axisPointerClazz = [];
  35402. AxisView.registerAxisPointerClass = function (type, clazz) {
  35403. if (__DEV__) {
  35404. if (axisPointerClazz[type]) {
  35405. throw new Error('axisPointer ' + type + ' exists');
  35406. }
  35407. }
  35408. axisPointerClazz[type] = clazz;
  35409. };
  35410. AxisView.getAxisPointerClass = function (type) {
  35411. return type && axisPointerClazz[type];
  35412. };
  35413. /*
  35414. * Licensed to the Apache Software Foundation (ASF) under one
  35415. * or more contributor license agreements. See the NOTICE file
  35416. * distributed with this work for additional information
  35417. * regarding copyright ownership. The ASF licenses this file
  35418. * to you under the Apache License, Version 2.0 (the
  35419. * "License"); you may not use this file except in compliance
  35420. * with the License. You may obtain a copy of the License at
  35421. *
  35422. * http://www.apache.org/licenses/LICENSE-2.0
  35423. *
  35424. * Unless required by applicable law or agreed to in writing,
  35425. * software distributed under the License is distributed on an
  35426. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35427. * KIND, either express or implied. See the License for the
  35428. * specific language governing permissions and limitations
  35429. * under the License.
  35430. */
  35431. /**
  35432. * Can only be called after coordinate system creation stage.
  35433. * (Can be called before coordinate system update stage).
  35434. *
  35435. * @param {Object} opt {labelInside}
  35436. * @return {Object} {
  35437. * position, rotation, labelDirection, labelOffset,
  35438. * tickDirection, labelRotate, z2
  35439. * }
  35440. */
  35441. function layout$1(gridModel, axisModel, opt) {
  35442. opt = opt || {};
  35443. var grid = gridModel.coordinateSystem;
  35444. var axis = axisModel.axis;
  35445. var layout = {};
  35446. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  35447. var rawAxisPosition = axis.position;
  35448. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  35449. var axisDim = axis.dim;
  35450. var rect = grid.getRect();
  35451. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  35452. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  35453. var axisOffset = axisModel.get('offset') || 0;
  35454. var posBound = axisDim === 'x'
  35455. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  35456. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  35457. if (otherAxisOnZeroOf) {
  35458. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  35459. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  35460. }
  35461. // Axis position
  35462. layout.position = [
  35463. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  35464. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  35465. ];
  35466. // Axis rotation
  35467. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  35468. // Tick and label direction, x y is axisDim
  35469. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  35470. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  35471. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  35472. if (axisModel.get('axisTick.inside')) {
  35473. layout.tickDirection = -layout.tickDirection;
  35474. }
  35475. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  35476. layout.labelDirection = -layout.labelDirection;
  35477. }
  35478. // Special label rotation
  35479. var labelRotate = axisModel.get('axisLabel.rotate');
  35480. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  35481. // Over splitLine and splitArea
  35482. layout.z2 = 1;
  35483. return layout;
  35484. }
  35485. /*
  35486. * Licensed to the Apache Software Foundation (ASF) under one
  35487. * or more contributor license agreements. See the NOTICE file
  35488. * distributed with this work for additional information
  35489. * regarding copyright ownership. The ASF licenses this file
  35490. * to you under the Apache License, Version 2.0 (the
  35491. * "License"); you may not use this file except in compliance
  35492. * with the License. You may obtain a copy of the License at
  35493. *
  35494. * http://www.apache.org/licenses/LICENSE-2.0
  35495. *
  35496. * Unless required by applicable law or agreed to in writing,
  35497. * software distributed under the License is distributed on an
  35498. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35499. * KIND, either express or implied. See the License for the
  35500. * specific language governing permissions and limitations
  35501. * under the License.
  35502. */
  35503. var axisBuilderAttrs = [
  35504. 'axisLine', 'axisTickLabel', 'axisName'
  35505. ];
  35506. var selfBuilderAttrs = [
  35507. 'splitArea', 'splitLine'
  35508. ];
  35509. // function getAlignWithLabel(model, axisModel) {
  35510. // var alignWithLabel = model.get('alignWithLabel');
  35511. // if (alignWithLabel === 'auto') {
  35512. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  35513. // }
  35514. // return alignWithLabel;
  35515. // }
  35516. var CartesianAxisView = AxisView.extend({
  35517. type: 'cartesianAxis',
  35518. axisPointerClass: 'CartesianAxisPointer',
  35519. /**
  35520. * @override
  35521. */
  35522. render: function (axisModel, ecModel, api, payload) {
  35523. this.group.removeAll();
  35524. var oldAxisGroup = this._axisGroup;
  35525. this._axisGroup = new Group();
  35526. this.group.add(this._axisGroup);
  35527. if (!axisModel.get('show')) {
  35528. return;
  35529. }
  35530. var gridModel = axisModel.getCoordSysModel();
  35531. var layout = layout$1(gridModel, axisModel);
  35532. var axisBuilder = new AxisBuilder(axisModel, layout);
  35533. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  35534. this._axisGroup.add(axisBuilder.getGroup());
  35535. each$1(selfBuilderAttrs, function (name) {
  35536. if (axisModel.get(name + '.show')) {
  35537. this['_' + name](axisModel, gridModel);
  35538. }
  35539. }, this);
  35540. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  35541. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  35542. },
  35543. remove: function () {
  35544. this._splitAreaColors = null;
  35545. },
  35546. /**
  35547. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35548. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35549. * @private
  35550. */
  35551. _splitLine: function (axisModel, gridModel) {
  35552. var axis = axisModel.axis;
  35553. if (axis.scale.isBlank()) {
  35554. return;
  35555. }
  35556. var splitLineModel = axisModel.getModel('splitLine');
  35557. var lineStyleModel = splitLineModel.getModel('lineStyle');
  35558. var lineColors = lineStyleModel.get('color');
  35559. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  35560. var gridRect = gridModel.coordinateSystem.getRect();
  35561. var isHorizontal = axis.isHorizontal();
  35562. var lineCount = 0;
  35563. var ticksCoords = axis.getTicksCoords({
  35564. tickModel: splitLineModel
  35565. });
  35566. var p1 = [];
  35567. var p2 = [];
  35568. // Simple optimization
  35569. // Batching the lines if color are the same
  35570. var lineStyle = lineStyleModel.getLineStyle();
  35571. for (var i = 0; i < ticksCoords.length; i++) {
  35572. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35573. if (isHorizontal) {
  35574. p1[0] = tickCoord;
  35575. p1[1] = gridRect.y;
  35576. p2[0] = tickCoord;
  35577. p2[1] = gridRect.y + gridRect.height;
  35578. }
  35579. else {
  35580. p1[0] = gridRect.x;
  35581. p1[1] = tickCoord;
  35582. p2[0] = gridRect.x + gridRect.width;
  35583. p2[1] = tickCoord;
  35584. }
  35585. var colorIndex = (lineCount++) % lineColors.length;
  35586. var tickValue = ticksCoords[i].tickValue;
  35587. this._axisGroup.add(new Line(subPixelOptimizeLine({
  35588. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  35589. shape: {
  35590. x1: p1[0],
  35591. y1: p1[1],
  35592. x2: p2[0],
  35593. y2: p2[1]
  35594. },
  35595. style: defaults({
  35596. stroke: lineColors[colorIndex]
  35597. }, lineStyle),
  35598. silent: true
  35599. })));
  35600. }
  35601. },
  35602. /**
  35603. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35604. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35605. * @private
  35606. */
  35607. _splitArea: function (axisModel, gridModel) {
  35608. var axis = axisModel.axis;
  35609. if (axis.scale.isBlank()) {
  35610. return;
  35611. }
  35612. var splitAreaModel = axisModel.getModel('splitArea');
  35613. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  35614. var areaColors = areaStyleModel.get('color');
  35615. var gridRect = gridModel.coordinateSystem.getRect();
  35616. var ticksCoords = axis.getTicksCoords({
  35617. tickModel: splitAreaModel,
  35618. clamp: true
  35619. });
  35620. if (!ticksCoords.length) {
  35621. return;
  35622. }
  35623. // For Making appropriate splitArea animation, the color and anid
  35624. // should be corresponding to previous one if possible.
  35625. var areaColorsLen = areaColors.length;
  35626. var lastSplitAreaColors = this._splitAreaColors;
  35627. var newSplitAreaColors = createHashMap();
  35628. var colorIndex = 0;
  35629. if (lastSplitAreaColors) {
  35630. for (var i = 0; i < ticksCoords.length; i++) {
  35631. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  35632. if (cIndex != null) {
  35633. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  35634. break;
  35635. }
  35636. }
  35637. }
  35638. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  35639. var areaStyle = areaStyleModel.getAreaStyle();
  35640. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  35641. for (var i = 1; i < ticksCoords.length; i++) {
  35642. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35643. var x;
  35644. var y;
  35645. var width;
  35646. var height;
  35647. if (axis.isHorizontal()) {
  35648. x = prev;
  35649. y = gridRect.y;
  35650. width = tickCoord - x;
  35651. height = gridRect.height;
  35652. prev = x + width;
  35653. }
  35654. else {
  35655. x = gridRect.x;
  35656. y = prev;
  35657. width = gridRect.width;
  35658. height = tickCoord - y;
  35659. prev = y + height;
  35660. }
  35661. var tickValue = ticksCoords[i - 1].tickValue;
  35662. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  35663. this._axisGroup.add(new Rect({
  35664. anid: tickValue != null ? 'area_' + tickValue : null,
  35665. shape: {
  35666. x: x,
  35667. y: y,
  35668. width: width,
  35669. height: height
  35670. },
  35671. style: defaults({
  35672. fill: areaColors[colorIndex]
  35673. }, areaStyle),
  35674. silent: true
  35675. }));
  35676. colorIndex = (colorIndex + 1) % areaColorsLen;
  35677. }
  35678. this._splitAreaColors = newSplitAreaColors;
  35679. }
  35680. });
  35681. CartesianAxisView.extend({
  35682. type: 'xAxis'
  35683. });
  35684. CartesianAxisView.extend({
  35685. type: 'yAxis'
  35686. });
  35687. /*
  35688. * Licensed to the Apache Software Foundation (ASF) under one
  35689. * or more contributor license agreements. See the NOTICE file
  35690. * distributed with this work for additional information
  35691. * regarding copyright ownership. The ASF licenses this file
  35692. * to you under the Apache License, Version 2.0 (the
  35693. * "License"); you may not use this file except in compliance
  35694. * with the License. You may obtain a copy of the License at
  35695. *
  35696. * http://www.apache.org/licenses/LICENSE-2.0
  35697. *
  35698. * Unless required by applicable law or agreed to in writing,
  35699. * software distributed under the License is distributed on an
  35700. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35701. * KIND, either express or implied. See the License for the
  35702. * specific language governing permissions and limitations
  35703. * under the License.
  35704. */
  35705. /*
  35706. * Licensed to the Apache Software Foundation (ASF) under one
  35707. * or more contributor license agreements. See the NOTICE file
  35708. * distributed with this work for additional information
  35709. * regarding copyright ownership. The ASF licenses this file
  35710. * to you under the Apache License, Version 2.0 (the
  35711. * "License"); you may not use this file except in compliance
  35712. * with the License. You may obtain a copy of the License at
  35713. *
  35714. * http://www.apache.org/licenses/LICENSE-2.0
  35715. *
  35716. * Unless required by applicable law or agreed to in writing,
  35717. * software distributed under the License is distributed on an
  35718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35719. * KIND, either express or implied. See the License for the
  35720. * specific language governing permissions and limitations
  35721. * under the License.
  35722. */
  35723. // Grid view
  35724. extendComponentView({
  35725. type: 'grid',
  35726. render: function (gridModel, ecModel) {
  35727. this.group.removeAll();
  35728. if (gridModel.get('show')) {
  35729. this.group.add(new Rect({
  35730. shape: gridModel.coordinateSystem.getRect(),
  35731. style: defaults({
  35732. fill: gridModel.get('backgroundColor')
  35733. }, gridModel.getItemStyle()),
  35734. silent: true,
  35735. z2: -1
  35736. }));
  35737. }
  35738. }
  35739. });
  35740. registerPreprocessor(function (option) {
  35741. // Only create grid when need
  35742. if (option.xAxis && option.yAxis && !option.grid) {
  35743. option.grid = {};
  35744. }
  35745. });
  35746. /*
  35747. * Licensed to the Apache Software Foundation (ASF) under one
  35748. * or more contributor license agreements. See the NOTICE file
  35749. * distributed with this work for additional information
  35750. * regarding copyright ownership. The ASF licenses this file
  35751. * to you under the Apache License, Version 2.0 (the
  35752. * "License"); you may not use this file except in compliance
  35753. * with the License. You may obtain a copy of the License at
  35754. *
  35755. * http://www.apache.org/licenses/LICENSE-2.0
  35756. *
  35757. * Unless required by applicable law or agreed to in writing,
  35758. * software distributed under the License is distributed on an
  35759. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35760. * KIND, either express or implied. See the License for the
  35761. * specific language governing permissions and limitations
  35762. * under the License.
  35763. */
  35764. // In case developer forget to include grid component
  35765. registerVisual(visualSymbol('line', 'circle', 'line'));
  35766. registerLayout(pointsLayout('line'));
  35767. // Down sample after filter
  35768. registerProcessor(
  35769. PRIORITY.PROCESSOR.STATISTIC,
  35770. dataSample('line')
  35771. );
  35772. /*
  35773. * Licensed to the Apache Software Foundation (ASF) under one
  35774. * or more contributor license agreements. See the NOTICE file
  35775. * distributed with this work for additional information
  35776. * regarding copyright ownership. The ASF licenses this file
  35777. * to you under the Apache License, Version 2.0 (the
  35778. * "License"); you may not use this file except in compliance
  35779. * with the License. You may obtain a copy of the License at
  35780. *
  35781. * http://www.apache.org/licenses/LICENSE-2.0
  35782. *
  35783. * Unless required by applicable law or agreed to in writing,
  35784. * software distributed under the License is distributed on an
  35785. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35786. * KIND, either express or implied. See the License for the
  35787. * specific language governing permissions and limitations
  35788. * under the License.
  35789. */
  35790. var BaseBarSeries = SeriesModel.extend({
  35791. type: 'series.__base_bar__',
  35792. getInitialData: function (option, ecModel) {
  35793. return createListFromArray(this.getSource(), this);
  35794. },
  35795. getMarkerPosition: function (value) {
  35796. var coordSys = this.coordinateSystem;
  35797. if (coordSys) {
  35798. // PENDING if clamp ?
  35799. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  35800. var data = this.getData();
  35801. var offset = data.getLayout('offset');
  35802. var size = data.getLayout('size');
  35803. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  35804. pt[offsetIndex] += offset + size / 2;
  35805. return pt;
  35806. }
  35807. return [NaN, NaN];
  35808. },
  35809. defaultOption: {
  35810. zlevel: 0, // 一级层叠
  35811. z: 2, // 二级层叠
  35812. coordinateSystem: 'cartesian2d',
  35813. legendHoverLink: true,
  35814. // stack: null
  35815. // Cartesian coordinate system
  35816. // xAxisIndex: 0,
  35817. // yAxisIndex: 0,
  35818. // 最小高度改为0
  35819. barMinHeight: 0,
  35820. // 最小角度为0,仅对极坐标系下的柱状图有效
  35821. barMinAngle: 0,
  35822. // cursor: null,
  35823. large: false,
  35824. largeThreshold: 400,
  35825. progressive: 3e3,
  35826. progressiveChunkMode: 'mod',
  35827. // barMaxWidth: null,
  35828. // 默认自适应
  35829. // barWidth: null,
  35830. // 柱间距离,默认为柱形宽度的30%,可设固定值
  35831. // barGap: '30%',
  35832. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  35833. // barCategoryGap: '20%',
  35834. // label: {
  35835. // show: false
  35836. // },
  35837. itemStyle: {},
  35838. emphasis: {}
  35839. }
  35840. });
  35841. /*
  35842. * Licensed to the Apache Software Foundation (ASF) under one
  35843. * or more contributor license agreements. See the NOTICE file
  35844. * distributed with this work for additional information
  35845. * regarding copyright ownership. The ASF licenses this file
  35846. * to you under the Apache License, Version 2.0 (the
  35847. * "License"); you may not use this file except in compliance
  35848. * with the License. You may obtain a copy of the License at
  35849. *
  35850. * http://www.apache.org/licenses/LICENSE-2.0
  35851. *
  35852. * Unless required by applicable law or agreed to in writing,
  35853. * software distributed under the License is distributed on an
  35854. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35855. * KIND, either express or implied. See the License for the
  35856. * specific language governing permissions and limitations
  35857. * under the License.
  35858. */
  35859. BaseBarSeries.extend({
  35860. type: 'series.bar',
  35861. dependencies: ['grid', 'polar'],
  35862. brushSelector: 'rect',
  35863. /**
  35864. * @override
  35865. */
  35866. getProgressive: function () {
  35867. // Do not support progressive in normal mode.
  35868. return this.get('large')
  35869. ? this.get('progressive')
  35870. : false;
  35871. },
  35872. /**
  35873. * @override
  35874. */
  35875. getProgressiveThreshold: function () {
  35876. // Do not support progressive in normal mode.
  35877. var progressiveThreshold = this.get('progressiveThreshold');
  35878. var largeThreshold = this.get('largeThreshold');
  35879. if (largeThreshold > progressiveThreshold) {
  35880. progressiveThreshold = largeThreshold;
  35881. }
  35882. return progressiveThreshold;
  35883. }
  35884. });
  35885. /*
  35886. * Licensed to the Apache Software Foundation (ASF) under one
  35887. * or more contributor license agreements. See the NOTICE file
  35888. * distributed with this work for additional information
  35889. * regarding copyright ownership. The ASF licenses this file
  35890. * to you under the Apache License, Version 2.0 (the
  35891. * "License"); you may not use this file except in compliance
  35892. * with the License. You may obtain a copy of the License at
  35893. *
  35894. * http://www.apache.org/licenses/LICENSE-2.0
  35895. *
  35896. * Unless required by applicable law or agreed to in writing,
  35897. * software distributed under the License is distributed on an
  35898. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35899. * KIND, either express or implied. See the License for the
  35900. * specific language governing permissions and limitations
  35901. * under the License.
  35902. */
  35903. function setLabel(
  35904. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  35905. ) {
  35906. var labelModel = itemModel.getModel('label');
  35907. var hoverLabelModel = itemModel.getModel('emphasis.label');
  35908. setLabelStyle(
  35909. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  35910. {
  35911. labelFetcher: seriesModel,
  35912. labelDataIndex: dataIndex,
  35913. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  35914. isRectText: true,
  35915. autoColor: color
  35916. }
  35917. );
  35918. fixPosition(normalStyle);
  35919. fixPosition(hoverStyle);
  35920. }
  35921. function fixPosition(style, labelPositionOutside) {
  35922. if (style.textPosition === 'outside') {
  35923. style.textPosition = labelPositionOutside;
  35924. }
  35925. }
  35926. /*
  35927. * Licensed to the Apache Software Foundation (ASF) under one
  35928. * or more contributor license agreements. See the NOTICE file
  35929. * distributed with this work for additional information
  35930. * regarding copyright ownership. The ASF licenses this file
  35931. * to you under the Apache License, Version 2.0 (the
  35932. * "License"); you may not use this file except in compliance
  35933. * with the License. You may obtain a copy of the License at
  35934. *
  35935. * http://www.apache.org/licenses/LICENSE-2.0
  35936. *
  35937. * Unless required by applicable law or agreed to in writing,
  35938. * software distributed under the License is distributed on an
  35939. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35940. * KIND, either express or implied. See the License for the
  35941. * specific language governing permissions and limitations
  35942. * under the License.
  35943. */
  35944. var getBarItemStyle = makeStyleMapper(
  35945. [
  35946. ['fill', 'color'],
  35947. ['stroke', 'borderColor'],
  35948. ['lineWidth', 'borderWidth'],
  35949. // Compatitable with 2
  35950. ['stroke', 'barBorderColor'],
  35951. ['lineWidth', 'barBorderWidth'],
  35952. ['opacity'],
  35953. ['shadowBlur'],
  35954. ['shadowOffsetX'],
  35955. ['shadowOffsetY'],
  35956. ['shadowColor']
  35957. ]
  35958. );
  35959. var barItemStyle = {
  35960. getBarItemStyle: function (excludes) {
  35961. var style = getBarItemStyle(this, excludes);
  35962. if (this.getBorderLineDash) {
  35963. var lineDash = this.getBorderLineDash();
  35964. lineDash && (style.lineDash = lineDash);
  35965. }
  35966. return style;
  35967. }
  35968. };
  35969. /*
  35970. * Licensed to the Apache Software Foundation (ASF) under one
  35971. * or more contributor license agreements. See the NOTICE file
  35972. * distributed with this work for additional information
  35973. * regarding copyright ownership. The ASF licenses this file
  35974. * to you under the Apache License, Version 2.0 (the
  35975. * "License"); you may not use this file except in compliance
  35976. * with the License. You may obtain a copy of the License at
  35977. *
  35978. * http://www.apache.org/licenses/LICENSE-2.0
  35979. *
  35980. * Unless required by applicable law or agreed to in writing,
  35981. * software distributed under the License is distributed on an
  35982. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35983. * KIND, either express or implied. See the License for the
  35984. * specific language governing permissions and limitations
  35985. * under the License.
  35986. */
  35987. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  35988. // FIXME
  35989. // Just for compatible with ec2.
  35990. extend(Model.prototype, barItemStyle);
  35991. extendChartView({
  35992. type: 'bar',
  35993. render: function (seriesModel, ecModel, api) {
  35994. this._updateDrawMode(seriesModel);
  35995. var coordinateSystemType = seriesModel.get('coordinateSystem');
  35996. if (coordinateSystemType === 'cartesian2d'
  35997. || coordinateSystemType === 'polar'
  35998. ) {
  35999. this._isLargeDraw
  36000. ? this._renderLarge(seriesModel, ecModel, api)
  36001. : this._renderNormal(seriesModel, ecModel, api);
  36002. }
  36003. else if (__DEV__) {
  36004. console.warn('Only cartesian2d and polar supported for bar.');
  36005. }
  36006. return this.group;
  36007. },
  36008. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  36009. this._clear();
  36010. this._updateDrawMode(seriesModel);
  36011. },
  36012. incrementalRender: function (params, seriesModel, ecModel, api) {
  36013. // Do not support progressive in normal mode.
  36014. this._incrementalRenderLarge(params, seriesModel);
  36015. },
  36016. _updateDrawMode: function (seriesModel) {
  36017. var isLargeDraw = seriesModel.pipelineContext.large;
  36018. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  36019. this._isLargeDraw = isLargeDraw;
  36020. this._clear();
  36021. }
  36022. },
  36023. _renderNormal: function (seriesModel, ecModel, api) {
  36024. var group = this.group;
  36025. var data = seriesModel.getData();
  36026. var oldData = this._data;
  36027. var coord = seriesModel.coordinateSystem;
  36028. var baseAxis = coord.getBaseAxis();
  36029. var isHorizontalOrRadial;
  36030. if (coord.type === 'cartesian2d') {
  36031. isHorizontalOrRadial = baseAxis.isHorizontal();
  36032. }
  36033. else if (coord.type === 'polar') {
  36034. isHorizontalOrRadial = baseAxis.dim === 'angle';
  36035. }
  36036. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  36037. data.diff(oldData)
  36038. .add(function (dataIndex) {
  36039. if (!data.hasValue(dataIndex)) {
  36040. return;
  36041. }
  36042. var itemModel = data.getItemModel(dataIndex);
  36043. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  36044. var el = elementCreator[coord.type](
  36045. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  36046. );
  36047. data.setItemGraphicEl(dataIndex, el);
  36048. group.add(el);
  36049. updateStyle(
  36050. el, data, dataIndex, itemModel, layout,
  36051. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  36052. );
  36053. })
  36054. .update(function (newIndex, oldIndex) {
  36055. var el = oldData.getItemGraphicEl(oldIndex);
  36056. if (!data.hasValue(newIndex)) {
  36057. group.remove(el);
  36058. return;
  36059. }
  36060. var itemModel = data.getItemModel(newIndex);
  36061. var layout = getLayout[coord.type](data, newIndex, itemModel);
  36062. if (el) {
  36063. updateProps(el, {shape: layout}, animationModel, newIndex);
  36064. }
  36065. else {
  36066. el = elementCreator[coord.type](
  36067. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  36068. );
  36069. }
  36070. data.setItemGraphicEl(newIndex, el);
  36071. // Add back
  36072. group.add(el);
  36073. updateStyle(
  36074. el, data, newIndex, itemModel, layout,
  36075. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  36076. );
  36077. })
  36078. .remove(function (dataIndex) {
  36079. var el = oldData.getItemGraphicEl(dataIndex);
  36080. if (coord.type === 'cartesian2d') {
  36081. el && removeRect(dataIndex, animationModel, el);
  36082. }
  36083. else {
  36084. el && removeSector(dataIndex, animationModel, el);
  36085. }
  36086. })
  36087. .execute();
  36088. this._data = data;
  36089. },
  36090. _renderLarge: function (seriesModel, ecModel, api) {
  36091. this._clear();
  36092. createLarge(seriesModel, this.group);
  36093. },
  36094. _incrementalRenderLarge: function (params, seriesModel) {
  36095. createLarge(seriesModel, this.group, true);
  36096. },
  36097. dispose: noop,
  36098. remove: function (ecModel) {
  36099. this._clear(ecModel);
  36100. },
  36101. _clear: function (ecModel) {
  36102. var group = this.group;
  36103. var data = this._data;
  36104. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  36105. data.eachItemGraphicEl(function (el) {
  36106. if (el.type === 'sector') {
  36107. removeSector(el.dataIndex, ecModel, el);
  36108. }
  36109. else {
  36110. removeRect(el.dataIndex, ecModel, el);
  36111. }
  36112. });
  36113. }
  36114. else {
  36115. group.removeAll();
  36116. }
  36117. this._data = null;
  36118. }
  36119. });
  36120. var elementCreator = {
  36121. cartesian2d: function (
  36122. data, dataIndex, itemModel, layout, isHorizontal,
  36123. animationModel, isUpdate
  36124. ) {
  36125. var rect = new Rect({shape: extend({}, layout)});
  36126. // Animation
  36127. if (animationModel) {
  36128. var rectShape = rect.shape;
  36129. var animateProperty = isHorizontal ? 'height' : 'width';
  36130. var animateTarget = {};
  36131. rectShape[animateProperty] = 0;
  36132. animateTarget[animateProperty] = layout[animateProperty];
  36133. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  36134. shape: animateTarget
  36135. }, animationModel, dataIndex);
  36136. }
  36137. return rect;
  36138. },
  36139. polar: function (
  36140. data, dataIndex, itemModel, layout, isRadial,
  36141. animationModel, isUpdate
  36142. ) {
  36143. // Keep the same logic with bar in catesion: use end value to control
  36144. // direction. Notice that if clockwise is true (by default), the sector
  36145. // will always draw clockwisely, no matter whether endAngle is greater
  36146. // or less than startAngle.
  36147. var clockwise = layout.startAngle < layout.endAngle;
  36148. var sector = new Sector({
  36149. shape: defaults({clockwise: clockwise}, layout)
  36150. });
  36151. // Animation
  36152. if (animationModel) {
  36153. var sectorShape = sector.shape;
  36154. var animateProperty = isRadial ? 'r' : 'endAngle';
  36155. var animateTarget = {};
  36156. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  36157. animateTarget[animateProperty] = layout[animateProperty];
  36158. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  36159. shape: animateTarget
  36160. }, animationModel, dataIndex);
  36161. }
  36162. return sector;
  36163. }
  36164. };
  36165. function removeRect(dataIndex, animationModel, el) {
  36166. // Not show text when animating
  36167. el.style.text = null;
  36168. updateProps(el, {
  36169. shape: {
  36170. width: 0
  36171. }
  36172. }, animationModel, dataIndex, function () {
  36173. el.parent && el.parent.remove(el);
  36174. });
  36175. }
  36176. function removeSector(dataIndex, animationModel, el) {
  36177. // Not show text when animating
  36178. el.style.text = null;
  36179. updateProps(el, {
  36180. shape: {
  36181. r: el.shape.r0
  36182. }
  36183. }, animationModel, dataIndex, function () {
  36184. el.parent && el.parent.remove(el);
  36185. });
  36186. }
  36187. var getLayout = {
  36188. cartesian2d: function (data, dataIndex, itemModel) {
  36189. var layout = data.getItemLayout(dataIndex);
  36190. var fixedLineWidth = getLineWidth(itemModel, layout);
  36191. // fix layout with lineWidth
  36192. var signX = layout.width > 0 ? 1 : -1;
  36193. var signY = layout.height > 0 ? 1 : -1;
  36194. return {
  36195. x: layout.x + signX * fixedLineWidth / 2,
  36196. y: layout.y + signY * fixedLineWidth / 2,
  36197. width: layout.width - signX * fixedLineWidth,
  36198. height: layout.height - signY * fixedLineWidth
  36199. };
  36200. },
  36201. polar: function (data, dataIndex, itemModel) {
  36202. var layout = data.getItemLayout(dataIndex);
  36203. return {
  36204. cx: layout.cx,
  36205. cy: layout.cy,
  36206. r0: layout.r0,
  36207. r: layout.r,
  36208. startAngle: layout.startAngle,
  36209. endAngle: layout.endAngle
  36210. };
  36211. }
  36212. };
  36213. function updateStyle(
  36214. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  36215. ) {
  36216. var color = data.getItemVisual(dataIndex, 'color');
  36217. var opacity = data.getItemVisual(dataIndex, 'opacity');
  36218. var itemStyleModel = itemModel.getModel('itemStyle');
  36219. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  36220. if (!isPolar) {
  36221. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  36222. }
  36223. el.useStyle(defaults(
  36224. {
  36225. fill: color,
  36226. opacity: opacity
  36227. },
  36228. itemStyleModel.getBarItemStyle()
  36229. ));
  36230. var cursorStyle = itemModel.getShallow('cursor');
  36231. cursorStyle && el.attr('cursor', cursorStyle);
  36232. var labelPositionOutside = isHorizontal
  36233. ? (layout.height > 0 ? 'bottom' : 'top')
  36234. : (layout.width > 0 ? 'left' : 'right');
  36235. if (!isPolar) {
  36236. setLabel(
  36237. el.style, hoverStyle, itemModel, color,
  36238. seriesModel, dataIndex, labelPositionOutside
  36239. );
  36240. }
  36241. setHoverStyle(el, hoverStyle);
  36242. }
  36243. // In case width or height are too small.
  36244. function getLineWidth(itemModel, rawLayout) {
  36245. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  36246. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  36247. }
  36248. var LargePath = Path.extend({
  36249. type: 'largeBar',
  36250. shape: {points: []},
  36251. buildPath: function (ctx, shape) {
  36252. // Drawing lines is more efficient than drawing
  36253. // a whole line or drawing rects.
  36254. var points = shape.points;
  36255. var startPoint = this.__startPoint;
  36256. var valueIdx = this.__valueIdx;
  36257. for (var i = 0; i < points.length; i += 2) {
  36258. startPoint[this.__valueIdx] = points[i + valueIdx];
  36259. ctx.moveTo(startPoint[0], startPoint[1]);
  36260. ctx.lineTo(points[i], points[i + 1]);
  36261. }
  36262. }
  36263. });
  36264. function createLarge(seriesModel, group, incremental) {
  36265. // TODO support polar
  36266. var data = seriesModel.getData();
  36267. var startPoint = [];
  36268. var valueIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  36269. startPoint[1 - valueIdx] = data.getLayout('valueAxisStart');
  36270. var el = new LargePath({
  36271. shape: {points: data.getLayout('largePoints')},
  36272. incremental: !!incremental,
  36273. __startPoint: startPoint,
  36274. __valueIdx: valueIdx
  36275. });
  36276. group.add(el);
  36277. setLargeStyle(el, seriesModel, data);
  36278. }
  36279. function setLargeStyle(el, seriesModel, data) {
  36280. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  36281. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  36282. el.useStyle(itemStyle);
  36283. el.style.fill = null;
  36284. el.style.stroke = borderColor;
  36285. el.style.lineWidth = data.getLayout('barWidth');
  36286. }
  36287. /*
  36288. * Licensed to the Apache Software Foundation (ASF) under one
  36289. * or more contributor license agreements. See the NOTICE file
  36290. * distributed with this work for additional information
  36291. * regarding copyright ownership. The ASF licenses this file
  36292. * to you under the Apache License, Version 2.0 (the
  36293. * "License"); you may not use this file except in compliance
  36294. * with the License. You may obtain a copy of the License at
  36295. *
  36296. * http://www.apache.org/licenses/LICENSE-2.0
  36297. *
  36298. * Unless required by applicable law or agreed to in writing,
  36299. * software distributed under the License is distributed on an
  36300. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36301. * KIND, either express or implied. See the License for the
  36302. * specific language governing permissions and limitations
  36303. * under the License.
  36304. */
  36305. // In case developer forget to include grid component
  36306. registerLayout(curry(layout, 'bar'));
  36307. // Should after normal bar layout, otherwise it is blocked by normal bar layout.
  36308. registerLayout(largeLayout);
  36309. registerVisual({
  36310. seriesType: 'bar',
  36311. reset: function (seriesModel) {
  36312. // Visual coding for legend
  36313. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  36314. }
  36315. });
  36316. /*
  36317. * Licensed to the Apache Software Foundation (ASF) under one
  36318. * or more contributor license agreements. See the NOTICE file
  36319. * distributed with this work for additional information
  36320. * regarding copyright ownership. The ASF licenses this file
  36321. * to you under the Apache License, Version 2.0 (the
  36322. * "License"); you may not use this file except in compliance
  36323. * with the License. You may obtain a copy of the License at
  36324. *
  36325. * http://www.apache.org/licenses/LICENSE-2.0
  36326. *
  36327. * Unless required by applicable law or agreed to in writing,
  36328. * software distributed under the License is distributed on an
  36329. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36330. * KIND, either express or implied. See the License for the
  36331. * specific language governing permissions and limitations
  36332. * under the License.
  36333. */
  36334. /**
  36335. * [Usage]:
  36336. * (1)
  36337. * createListSimply(seriesModel, ['value']);
  36338. * (2)
  36339. * createListSimply(seriesModel, {
  36340. * coordDimensions: ['value'],
  36341. * dimensionsCount: 5
  36342. * });
  36343. *
  36344. * @param {module:echarts/model/Series} seriesModel
  36345. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  36346. * The options in opt, see `echarts/data/helper/createDimensions`
  36347. * @param {Array.<string>} [nameList]
  36348. * @return {module:echarts/data/List}
  36349. */
  36350. var createListSimply = function (seriesModel, opt, nameList) {
  36351. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  36352. var source = seriesModel.getSource();
  36353. var dimensionsInfo = createDimensions(source, opt);
  36354. var list = new List(dimensionsInfo, seriesModel);
  36355. list.initData(source, nameList);
  36356. return list;
  36357. };
  36358. /*
  36359. * Licensed to the Apache Software Foundation (ASF) under one
  36360. * or more contributor license agreements. See the NOTICE file
  36361. * distributed with this work for additional information
  36362. * regarding copyright ownership. The ASF licenses this file
  36363. * to you under the Apache License, Version 2.0 (the
  36364. * "License"); you may not use this file except in compliance
  36365. * with the License. You may obtain a copy of the License at
  36366. *
  36367. * http://www.apache.org/licenses/LICENSE-2.0
  36368. *
  36369. * Unless required by applicable law or agreed to in writing,
  36370. * software distributed under the License is distributed on an
  36371. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36372. * KIND, either express or implied. See the License for the
  36373. * specific language governing permissions and limitations
  36374. * under the License.
  36375. */
  36376. /**
  36377. * Data selectable mixin for chart series.
  36378. * To eanble data select, option of series must have `selectedMode`.
  36379. * And each data item will use `selected` to toggle itself selected status
  36380. */
  36381. var selectableMixin = {
  36382. /**
  36383. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  36384. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  36385. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  36386. */
  36387. updateSelectedMap: function (targetList) {
  36388. this._targetList = isArray(targetList) ? targetList.slice() : [];
  36389. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  36390. targetMap.set(target.name, target);
  36391. return targetMap;
  36392. }, createHashMap());
  36393. },
  36394. /**
  36395. * Either name or id should be passed as input here.
  36396. * If both of them are defined, id is used.
  36397. *
  36398. * @param {string|undefined} name name of data
  36399. * @param {number|undefined} id dataIndex of data
  36400. */
  36401. // PENGING If selectedMode is null ?
  36402. select: function (name, id) {
  36403. var target = id != null
  36404. ? this._targetList[id]
  36405. : this._selectTargetMap.get(name);
  36406. var selectedMode = this.get('selectedMode');
  36407. if (selectedMode === 'single') {
  36408. this._selectTargetMap.each(function (target) {
  36409. target.selected = false;
  36410. });
  36411. }
  36412. target && (target.selected = true);
  36413. },
  36414. /**
  36415. * Either name or id should be passed as input here.
  36416. * If both of them are defined, id is used.
  36417. *
  36418. * @param {string|undefined} name name of data
  36419. * @param {number|undefined} id dataIndex of data
  36420. */
  36421. unSelect: function (name, id) {
  36422. var target = id != null
  36423. ? this._targetList[id]
  36424. : this._selectTargetMap.get(name);
  36425. // var selectedMode = this.get('selectedMode');
  36426. // selectedMode !== 'single' && target && (target.selected = false);
  36427. target && (target.selected = false);
  36428. },
  36429. /**
  36430. * Either name or id should be passed as input here.
  36431. * If both of them are defined, id is used.
  36432. *
  36433. * @param {string|undefined} name name of data
  36434. * @param {number|undefined} id dataIndex of data
  36435. */
  36436. toggleSelected: function (name, id) {
  36437. var target = id != null
  36438. ? this._targetList[id]
  36439. : this._selectTargetMap.get(name);
  36440. if (target != null) {
  36441. this[target.selected ? 'unSelect' : 'select'](name, id);
  36442. return target.selected;
  36443. }
  36444. },
  36445. /**
  36446. * Either name or id should be passed as input here.
  36447. * If both of them are defined, id is used.
  36448. *
  36449. * @param {string|undefined} name name of data
  36450. * @param {number|undefined} id dataIndex of data
  36451. */
  36452. isSelected: function (name, id) {
  36453. var target = id != null
  36454. ? this._targetList[id]
  36455. : this._selectTargetMap.get(name);
  36456. return target && target.selected;
  36457. }
  36458. };
  36459. /*
  36460. * Licensed to the Apache Software Foundation (ASF) under one
  36461. * or more contributor license agreements. See the NOTICE file
  36462. * distributed with this work for additional information
  36463. * regarding copyright ownership. The ASF licenses this file
  36464. * to you under the Apache License, Version 2.0 (the
  36465. * "License"); you may not use this file except in compliance
  36466. * with the License. You may obtain a copy of the License at
  36467. *
  36468. * http://www.apache.org/licenses/LICENSE-2.0
  36469. *
  36470. * Unless required by applicable law or agreed to in writing,
  36471. * software distributed under the License is distributed on an
  36472. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36473. * KIND, either express or implied. See the License for the
  36474. * specific language governing permissions and limitations
  36475. * under the License.
  36476. */
  36477. var PieSeries = extendSeriesModel({
  36478. type: 'series.pie',
  36479. // Overwrite
  36480. init: function (option) {
  36481. PieSeries.superApply(this, 'init', arguments);
  36482. // Enable legend selection for each data item
  36483. // Use a function instead of direct access because data reference may changed
  36484. this.legendDataProvider = function () {
  36485. return this.getRawData();
  36486. };
  36487. this.updateSelectedMap(this._createSelectableList());
  36488. this._defaultLabelLine(option);
  36489. },
  36490. // Overwrite
  36491. mergeOption: function (newOption) {
  36492. PieSeries.superCall(this, 'mergeOption', newOption);
  36493. this.updateSelectedMap(this._createSelectableList());
  36494. },
  36495. getInitialData: function (option, ecModel) {
  36496. return createListSimply(this, ['value']);
  36497. },
  36498. _createSelectableList: function () {
  36499. var data = this.getRawData();
  36500. var valueDim = data.mapDimension('value');
  36501. var targetList = [];
  36502. for (var i = 0, len = data.count(); i < len; i++) {
  36503. targetList.push({
  36504. name: data.getName(i),
  36505. value: data.get(valueDim, i),
  36506. selected: retrieveRawAttr(data, i, 'selected')
  36507. });
  36508. }
  36509. return targetList;
  36510. },
  36511. // Overwrite
  36512. getDataParams: function (dataIndex) {
  36513. var data = this.getData();
  36514. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  36515. // FIXME toFixed?
  36516. var valueList = [];
  36517. data.each(data.mapDimension('value'), function (value) {
  36518. valueList.push(value);
  36519. });
  36520. params.percent = getPercentWithPrecision(
  36521. valueList,
  36522. dataIndex,
  36523. data.hostModel.get('percentPrecision')
  36524. );
  36525. params.$vars.push('percent');
  36526. return params;
  36527. },
  36528. _defaultLabelLine: function (option) {
  36529. // Extend labelLine emphasis
  36530. defaultEmphasis(option, 'labelLine', ['show']);
  36531. var labelLineNormalOpt = option.labelLine;
  36532. var labelLineEmphasisOpt = option.emphasis.labelLine;
  36533. // Not show label line if `label.normal.show = false`
  36534. labelLineNormalOpt.show = labelLineNormalOpt.show
  36535. && option.label.show;
  36536. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  36537. && option.emphasis.label.show;
  36538. },
  36539. defaultOption: {
  36540. zlevel: 0,
  36541. z: 2,
  36542. legendHoverLink: true,
  36543. hoverAnimation: true,
  36544. // 默认全局居中
  36545. center: ['50%', '50%'],
  36546. radius: [0, '75%'],
  36547. // 默认顺时针
  36548. clockwise: true,
  36549. startAngle: 90,
  36550. // 最小角度改为0
  36551. minAngle: 0,
  36552. // 选中时扇区偏移量
  36553. selectedOffset: 10,
  36554. // 高亮扇区偏移量
  36555. hoverOffset: 10,
  36556. // If use strategy to avoid label overlapping
  36557. avoidLabelOverlap: true,
  36558. // 选择模式,默认关闭,可选single,multiple
  36559. // selectedMode: false,
  36560. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  36561. // roseType: null,
  36562. percentPrecision: 2,
  36563. // If still show when all data zero.
  36564. stillShowZeroSum: true,
  36565. // cursor: null,
  36566. label: {
  36567. // If rotate around circle
  36568. rotate: false,
  36569. show: true,
  36570. // 'outer', 'inside', 'center'
  36571. position: 'outer'
  36572. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  36573. // 默认使用全局文本样式,详见TEXTSTYLE
  36574. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  36575. },
  36576. // Enabled when label.normal.position is 'outer'
  36577. labelLine: {
  36578. show: true,
  36579. // 引导线两段中的第一段长度
  36580. length: 15,
  36581. // 引导线两段中的第二段长度
  36582. length2: 15,
  36583. smooth: false,
  36584. lineStyle: {
  36585. // color: 各异,
  36586. width: 1,
  36587. type: 'solid'
  36588. }
  36589. },
  36590. itemStyle: {
  36591. borderWidth: 1
  36592. },
  36593. // Animation type canbe expansion, scale
  36594. animationType: 'expansion',
  36595. animationEasing: 'cubicOut'
  36596. }
  36597. });
  36598. mixin(PieSeries, selectableMixin);
  36599. /*
  36600. * Licensed to the Apache Software Foundation (ASF) under one
  36601. * or more contributor license agreements. See the NOTICE file
  36602. * distributed with this work for additional information
  36603. * regarding copyright ownership. The ASF licenses this file
  36604. * to you under the Apache License, Version 2.0 (the
  36605. * "License"); you may not use this file except in compliance
  36606. * with the License. You may obtain a copy of the License at
  36607. *
  36608. * http://www.apache.org/licenses/LICENSE-2.0
  36609. *
  36610. * Unless required by applicable law or agreed to in writing,
  36611. * software distributed under the License is distributed on an
  36612. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36613. * KIND, either express or implied. See the License for the
  36614. * specific language governing permissions and limitations
  36615. * under the License.
  36616. */
  36617. /**
  36618. * @param {module:echarts/model/Series} seriesModel
  36619. * @param {boolean} hasAnimation
  36620. * @inner
  36621. */
  36622. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  36623. var data = seriesModel.getData();
  36624. var dataIndex = this.dataIndex;
  36625. var name = data.getName(dataIndex);
  36626. var selectedOffset = seriesModel.get('selectedOffset');
  36627. api.dispatchAction({
  36628. type: 'pieToggleSelect',
  36629. from: uid,
  36630. name: name,
  36631. seriesId: seriesModel.id
  36632. });
  36633. data.each(function (idx) {
  36634. toggleItemSelected(
  36635. data.getItemGraphicEl(idx),
  36636. data.getItemLayout(idx),
  36637. seriesModel.isSelected(data.getName(idx)),
  36638. selectedOffset,
  36639. hasAnimation
  36640. );
  36641. });
  36642. }
  36643. /**
  36644. * @param {module:zrender/graphic/Sector} el
  36645. * @param {Object} layout
  36646. * @param {boolean} isSelected
  36647. * @param {number} selectedOffset
  36648. * @param {boolean} hasAnimation
  36649. * @inner
  36650. */
  36651. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  36652. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  36653. var dx = Math.cos(midAngle);
  36654. var dy = Math.sin(midAngle);
  36655. var offset = isSelected ? selectedOffset : 0;
  36656. var position = [dx * offset, dy * offset];
  36657. hasAnimation
  36658. // animateTo will stop revious animation like update transition
  36659. ? el.animate()
  36660. .when(200, {
  36661. position: position
  36662. })
  36663. .start('bounceOut')
  36664. : el.attr('position', position);
  36665. }
  36666. /**
  36667. * Piece of pie including Sector, Label, LabelLine
  36668. * @constructor
  36669. * @extends {module:zrender/graphic/Group}
  36670. */
  36671. function PiePiece(data, idx) {
  36672. Group.call(this);
  36673. var sector = new Sector({
  36674. z2: 2
  36675. });
  36676. var polyline = new Polyline();
  36677. var text = new Text();
  36678. this.add(sector);
  36679. this.add(polyline);
  36680. this.add(text);
  36681. this.updateData(data, idx, true);
  36682. // Hover to change label and labelLine
  36683. function onEmphasis() {
  36684. polyline.ignore = polyline.hoverIgnore;
  36685. text.ignore = text.hoverIgnore;
  36686. }
  36687. function onNormal() {
  36688. polyline.ignore = polyline.normalIgnore;
  36689. text.ignore = text.normalIgnore;
  36690. }
  36691. this.on('emphasis', onEmphasis)
  36692. .on('normal', onNormal)
  36693. .on('mouseover', onEmphasis)
  36694. .on('mouseout', onNormal);
  36695. }
  36696. var piePieceProto = PiePiece.prototype;
  36697. piePieceProto.updateData = function (data, idx, firstCreate) {
  36698. var sector = this.childAt(0);
  36699. var seriesModel = data.hostModel;
  36700. var itemModel = data.getItemModel(idx);
  36701. var layout = data.getItemLayout(idx);
  36702. var sectorShape = extend({}, layout);
  36703. sectorShape.label = null;
  36704. if (firstCreate) {
  36705. sector.setShape(sectorShape);
  36706. var animationType = seriesModel.getShallow('animationType');
  36707. if (animationType === 'scale') {
  36708. sector.shape.r = layout.r0;
  36709. initProps(sector, {
  36710. shape: {
  36711. r: layout.r
  36712. }
  36713. }, seriesModel, idx);
  36714. }
  36715. // Expansion
  36716. else {
  36717. sector.shape.endAngle = layout.startAngle;
  36718. updateProps(sector, {
  36719. shape: {
  36720. endAngle: layout.endAngle
  36721. }
  36722. }, seriesModel, idx);
  36723. }
  36724. }
  36725. else {
  36726. updateProps(sector, {
  36727. shape: sectorShape
  36728. }, seriesModel, idx);
  36729. }
  36730. // Update common style
  36731. var visualColor = data.getItemVisual(idx, 'color');
  36732. sector.useStyle(
  36733. defaults(
  36734. {
  36735. lineJoin: 'bevel',
  36736. fill: visualColor
  36737. },
  36738. itemModel.getModel('itemStyle').getItemStyle()
  36739. )
  36740. );
  36741. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  36742. var cursorStyle = itemModel.getShallow('cursor');
  36743. cursorStyle && sector.attr('cursor', cursorStyle);
  36744. // Toggle selected
  36745. toggleItemSelected(
  36746. this,
  36747. data.getItemLayout(idx),
  36748. seriesModel.isSelected(null, idx),
  36749. seriesModel.get('selectedOffset'),
  36750. seriesModel.get('animation')
  36751. );
  36752. function onEmphasis() {
  36753. // Sector may has animation of updating data. Force to move to the last frame
  36754. // Or it may stopped on the wrong shape
  36755. sector.stopAnimation(true);
  36756. sector.animateTo({
  36757. shape: {
  36758. r: layout.r + seriesModel.get('hoverOffset')
  36759. }
  36760. }, 300, 'elasticOut');
  36761. }
  36762. function onNormal() {
  36763. sector.stopAnimation(true);
  36764. sector.animateTo({
  36765. shape: {
  36766. r: layout.r
  36767. }
  36768. }, 300, 'elasticOut');
  36769. }
  36770. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  36771. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  36772. sector
  36773. .on('mouseover', onEmphasis)
  36774. .on('mouseout', onNormal)
  36775. .on('emphasis', onEmphasis)
  36776. .on('normal', onNormal);
  36777. }
  36778. this._updateLabel(data, idx);
  36779. setHoverStyle(this);
  36780. };
  36781. piePieceProto._updateLabel = function (data, idx) {
  36782. var labelLine = this.childAt(1);
  36783. var labelText = this.childAt(2);
  36784. var seriesModel = data.hostModel;
  36785. var itemModel = data.getItemModel(idx);
  36786. var layout = data.getItemLayout(idx);
  36787. var labelLayout = layout.label;
  36788. var visualColor = data.getItemVisual(idx, 'color');
  36789. updateProps(labelLine, {
  36790. shape: {
  36791. points: labelLayout.linePoints || [
  36792. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  36793. ]
  36794. }
  36795. }, seriesModel, idx);
  36796. updateProps(labelText, {
  36797. style: {
  36798. x: labelLayout.x,
  36799. y: labelLayout.y
  36800. }
  36801. }, seriesModel, idx);
  36802. labelText.attr({
  36803. rotation: labelLayout.rotation,
  36804. origin: [labelLayout.x, labelLayout.y],
  36805. z2: 10
  36806. });
  36807. var labelModel = itemModel.getModel('label');
  36808. var labelHoverModel = itemModel.getModel('emphasis.label');
  36809. var labelLineModel = itemModel.getModel('labelLine');
  36810. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  36811. var visualColor = data.getItemVisual(idx, 'color');
  36812. setLabelStyle(
  36813. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  36814. {
  36815. labelFetcher: data.hostModel,
  36816. labelDataIndex: idx,
  36817. defaultText: data.getName(idx),
  36818. autoColor: visualColor,
  36819. useInsideStyle: !!labelLayout.inside
  36820. },
  36821. {
  36822. textAlign: labelLayout.textAlign,
  36823. textVerticalAlign: labelLayout.verticalAlign,
  36824. opacity: data.getItemVisual(idx, 'opacity')
  36825. }
  36826. );
  36827. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  36828. labelText.hoverIgnore = !labelHoverModel.get('show');
  36829. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  36830. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  36831. // Default use item visual color
  36832. labelLine.setStyle({
  36833. stroke: visualColor,
  36834. opacity: data.getItemVisual(idx, 'opacity')
  36835. });
  36836. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  36837. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  36838. var smooth = labelLineModel.get('smooth');
  36839. if (smooth && smooth === true) {
  36840. smooth = 0.4;
  36841. }
  36842. labelLine.setShape({
  36843. smooth: smooth
  36844. });
  36845. };
  36846. inherits(PiePiece, Group);
  36847. // Pie view
  36848. var PieView = Chart.extend({
  36849. type: 'pie',
  36850. init: function () {
  36851. var sectorGroup = new Group();
  36852. this._sectorGroup = sectorGroup;
  36853. },
  36854. render: function (seriesModel, ecModel, api, payload) {
  36855. if (payload && (payload.from === this.uid)) {
  36856. return;
  36857. }
  36858. var data = seriesModel.getData();
  36859. var oldData = this._data;
  36860. var group = this.group;
  36861. var hasAnimation = ecModel.get('animation');
  36862. var isFirstRender = !oldData;
  36863. var animationType = seriesModel.get('animationType');
  36864. var onSectorClick = curry(
  36865. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  36866. );
  36867. var selectedMode = seriesModel.get('selectedMode');
  36868. data.diff(oldData)
  36869. .add(function (idx) {
  36870. var piePiece = new PiePiece(data, idx);
  36871. // Default expansion animation
  36872. if (isFirstRender && animationType !== 'scale') {
  36873. piePiece.eachChild(function (child) {
  36874. child.stopAnimation(true);
  36875. });
  36876. }
  36877. selectedMode && piePiece.on('click', onSectorClick);
  36878. data.setItemGraphicEl(idx, piePiece);
  36879. group.add(piePiece);
  36880. })
  36881. .update(function (newIdx, oldIdx) {
  36882. var piePiece = oldData.getItemGraphicEl(oldIdx);
  36883. piePiece.updateData(data, newIdx);
  36884. piePiece.off('click');
  36885. selectedMode && piePiece.on('click', onSectorClick);
  36886. group.add(piePiece);
  36887. data.setItemGraphicEl(newIdx, piePiece);
  36888. })
  36889. .remove(function (idx) {
  36890. var piePiece = oldData.getItemGraphicEl(idx);
  36891. group.remove(piePiece);
  36892. })
  36893. .execute();
  36894. if (
  36895. hasAnimation && isFirstRender && data.count() > 0
  36896. // Default expansion animation
  36897. && animationType !== 'scale'
  36898. ) {
  36899. var shape = data.getItemLayout(0);
  36900. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  36901. var removeClipPath = bind(group.removeClipPath, group);
  36902. group.setClipPath(this._createClipPath(
  36903. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  36904. ));
  36905. }
  36906. else {
  36907. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  36908. group.removeClipPath();
  36909. }
  36910. this._data = data;
  36911. },
  36912. dispose: function () {},
  36913. _createClipPath: function (
  36914. cx, cy, r, startAngle, clockwise, cb, seriesModel
  36915. ) {
  36916. var clipPath = new Sector({
  36917. shape: {
  36918. cx: cx,
  36919. cy: cy,
  36920. r0: 0,
  36921. r: r,
  36922. startAngle: startAngle,
  36923. endAngle: startAngle,
  36924. clockwise: clockwise
  36925. }
  36926. });
  36927. initProps(clipPath, {
  36928. shape: {
  36929. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  36930. }
  36931. }, seriesModel, cb);
  36932. return clipPath;
  36933. },
  36934. /**
  36935. * @implement
  36936. */
  36937. containPoint: function (point, seriesModel) {
  36938. var data = seriesModel.getData();
  36939. var itemLayout = data.getItemLayout(0);
  36940. if (itemLayout) {
  36941. var dx = point[0] - itemLayout.cx;
  36942. var dy = point[1] - itemLayout.cy;
  36943. var radius = Math.sqrt(dx * dx + dy * dy);
  36944. return radius <= itemLayout.r && radius >= itemLayout.r0;
  36945. }
  36946. }
  36947. });
  36948. /*
  36949. * Licensed to the Apache Software Foundation (ASF) under one
  36950. * or more contributor license agreements. See the NOTICE file
  36951. * distributed with this work for additional information
  36952. * regarding copyright ownership. The ASF licenses this file
  36953. * to you under the Apache License, Version 2.0 (the
  36954. * "License"); you may not use this file except in compliance
  36955. * with the License. You may obtain a copy of the License at
  36956. *
  36957. * http://www.apache.org/licenses/LICENSE-2.0
  36958. *
  36959. * Unless required by applicable law or agreed to in writing,
  36960. * software distributed under the License is distributed on an
  36961. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36962. * KIND, either express or implied. See the License for the
  36963. * specific language governing permissions and limitations
  36964. * under the License.
  36965. */
  36966. var createDataSelectAction = function (seriesType, actionInfos) {
  36967. each$1(actionInfos, function (actionInfo) {
  36968. actionInfo.update = 'updateView';
  36969. /**
  36970. * @payload
  36971. * @property {string} seriesName
  36972. * @property {string} name
  36973. */
  36974. registerAction(actionInfo, function (payload, ecModel) {
  36975. var selected = {};
  36976. ecModel.eachComponent(
  36977. {mainType: 'series', subType: seriesType, query: payload},
  36978. function (seriesModel) {
  36979. if (seriesModel[actionInfo.method]) {
  36980. seriesModel[actionInfo.method](
  36981. payload.name,
  36982. payload.dataIndex
  36983. );
  36984. }
  36985. var data = seriesModel.getData();
  36986. // Create selected map
  36987. data.each(function (idx) {
  36988. var name = data.getName(idx);
  36989. selected[name] = seriesModel.isSelected(name)
  36990. || false;
  36991. });
  36992. }
  36993. );
  36994. return {
  36995. name: payload.name,
  36996. selected: selected
  36997. };
  36998. });
  36999. });
  37000. };
  37001. /*
  37002. * Licensed to the Apache Software Foundation (ASF) under one
  37003. * or more contributor license agreements. See the NOTICE file
  37004. * distributed with this work for additional information
  37005. * regarding copyright ownership. The ASF licenses this file
  37006. * to you under the Apache License, Version 2.0 (the
  37007. * "License"); you may not use this file except in compliance
  37008. * with the License. You may obtain a copy of the License at
  37009. *
  37010. * http://www.apache.org/licenses/LICENSE-2.0
  37011. *
  37012. * Unless required by applicable law or agreed to in writing,
  37013. * software distributed under the License is distributed on an
  37014. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37015. * KIND, either express or implied. See the License for the
  37016. * specific language governing permissions and limitations
  37017. * under the License.
  37018. */
  37019. // Pick color from palette for each data item.
  37020. // Applicable for charts that require applying color palette
  37021. // in data level (like pie, funnel, chord).
  37022. var dataColor = function (seriesType) {
  37023. return {
  37024. getTargetSeries: function (ecModel) {
  37025. // Pie and funnel may use diferrent scope
  37026. var paletteScope = {};
  37027. var seiresModelMap = createHashMap();
  37028. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  37029. seriesModel.__paletteScope = paletteScope;
  37030. seiresModelMap.set(seriesModel.uid, seriesModel);
  37031. });
  37032. return seiresModelMap;
  37033. },
  37034. reset: function (seriesModel, ecModel) {
  37035. var dataAll = seriesModel.getRawData();
  37036. var idxMap = {};
  37037. var data = seriesModel.getData();
  37038. data.each(function (idx) {
  37039. var rawIdx = data.getRawIndex(idx);
  37040. idxMap[rawIdx] = idx;
  37041. });
  37042. dataAll.each(function (rawIdx) {
  37043. var filteredIdx = idxMap[rawIdx];
  37044. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  37045. var singleDataColor = filteredIdx != null
  37046. && data.getItemVisual(filteredIdx, 'color', true);
  37047. if (!singleDataColor) {
  37048. // FIXME Performance
  37049. var itemModel = dataAll.getItemModel(rawIdx);
  37050. var color = itemModel.get('itemStyle.color')
  37051. || seriesModel.getColorFromPalette(
  37052. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  37053. dataAll.count()
  37054. );
  37055. // Legend may use the visual info in data before processed
  37056. dataAll.setItemVisual(rawIdx, 'color', color);
  37057. // Data is not filtered
  37058. if (filteredIdx != null) {
  37059. data.setItemVisual(filteredIdx, 'color', color);
  37060. }
  37061. }
  37062. else {
  37063. // Set data all color for legend
  37064. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  37065. }
  37066. });
  37067. }
  37068. };
  37069. };
  37070. /*
  37071. * Licensed to the Apache Software Foundation (ASF) under one
  37072. * or more contributor license agreements. See the NOTICE file
  37073. * distributed with this work for additional information
  37074. * regarding copyright ownership. The ASF licenses this file
  37075. * to you under the Apache License, Version 2.0 (the
  37076. * "License"); you may not use this file except in compliance
  37077. * with the License. You may obtain a copy of the License at
  37078. *
  37079. * http://www.apache.org/licenses/LICENSE-2.0
  37080. *
  37081. * Unless required by applicable law or agreed to in writing,
  37082. * software distributed under the License is distributed on an
  37083. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37084. * KIND, either express or implied. See the License for the
  37085. * specific language governing permissions and limitations
  37086. * under the License.
  37087. */
  37088. // FIXME emphasis label position is not same with normal label position
  37089. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  37090. list.sort(function (a, b) {
  37091. return a.y - b.y;
  37092. });
  37093. function shiftDown(start, end, delta, dir) {
  37094. for (var j = start; j < end; j++) {
  37095. list[j].y += delta;
  37096. if (j > start
  37097. && j + 1 < end
  37098. && list[j + 1].y > list[j].y + list[j].height
  37099. ) {
  37100. shiftUp(j, delta / 2);
  37101. return;
  37102. }
  37103. }
  37104. shiftUp(end - 1, delta / 2);
  37105. }
  37106. function shiftUp(end, delta) {
  37107. for (var j = end; j >= 0; j--) {
  37108. list[j].y -= delta;
  37109. if (j > 0
  37110. && list[j].y > list[j - 1].y + list[j - 1].height
  37111. ) {
  37112. break;
  37113. }
  37114. }
  37115. }
  37116. function changeX(list, isDownList, cx, cy, r, dir) {
  37117. var lastDeltaX = dir > 0
  37118. ? isDownList // right-side
  37119. ? Number.MAX_VALUE // down
  37120. : 0 // up
  37121. : isDownList // left-side
  37122. ? Number.MAX_VALUE // down
  37123. : 0; // up
  37124. for (var i = 0, l = list.length; i < l; i++) {
  37125. var deltaY = Math.abs(list[i].y - cy);
  37126. var length = list[i].len;
  37127. var length2 = list[i].len2;
  37128. var deltaX = (deltaY < r + length)
  37129. ? Math.sqrt(
  37130. (r + length + length2) * (r + length + length2)
  37131. - deltaY * deltaY
  37132. )
  37133. : Math.abs(list[i].x - cx);
  37134. if (isDownList && deltaX >= lastDeltaX) {
  37135. // right-down, left-down
  37136. deltaX = lastDeltaX - 10;
  37137. }
  37138. if (!isDownList && deltaX <= lastDeltaX) {
  37139. // right-up, left-up
  37140. deltaX = lastDeltaX + 10;
  37141. }
  37142. list[i].x = cx + deltaX * dir;
  37143. lastDeltaX = deltaX;
  37144. }
  37145. }
  37146. var lastY = 0;
  37147. var delta;
  37148. var len = list.length;
  37149. var upList = [];
  37150. var downList = [];
  37151. for (var i = 0; i < len; i++) {
  37152. delta = list[i].y - lastY;
  37153. if (delta < 0) {
  37154. shiftDown(i, len, -delta, dir);
  37155. }
  37156. lastY = list[i].y + list[i].height;
  37157. }
  37158. if (viewHeight - lastY < 0) {
  37159. shiftUp(len - 1, lastY - viewHeight);
  37160. }
  37161. for (var i = 0; i < len; i++) {
  37162. if (list[i].y >= cy) {
  37163. downList.push(list[i]);
  37164. }
  37165. else {
  37166. upList.push(list[i]);
  37167. }
  37168. }
  37169. changeX(upList, false, cx, cy, r, dir);
  37170. changeX(downList, true, cx, cy, r, dir);
  37171. }
  37172. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  37173. var leftList = [];
  37174. var rightList = [];
  37175. for (var i = 0; i < labelLayoutList.length; i++) {
  37176. if (isPositionCenter(labelLayoutList[i])) {
  37177. continue;
  37178. }
  37179. if (labelLayoutList[i].x < cx) {
  37180. leftList.push(labelLayoutList[i]);
  37181. }
  37182. else {
  37183. rightList.push(labelLayoutList[i]);
  37184. }
  37185. }
  37186. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  37187. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  37188. for (var i = 0; i < labelLayoutList.length; i++) {
  37189. if (isPositionCenter(labelLayoutList[i])) {
  37190. continue;
  37191. }
  37192. var linePoints = labelLayoutList[i].linePoints;
  37193. if (linePoints) {
  37194. var dist = linePoints[1][0] - linePoints[2][0];
  37195. if (labelLayoutList[i].x < cx) {
  37196. linePoints[2][0] = labelLayoutList[i].x + 3;
  37197. }
  37198. else {
  37199. linePoints[2][0] = labelLayoutList[i].x - 3;
  37200. }
  37201. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  37202. linePoints[1][0] = linePoints[2][0] + dist;
  37203. }
  37204. }
  37205. }
  37206. function isPositionCenter(layout) {
  37207. // Not change x for center label
  37208. return layout.position === 'center';
  37209. }
  37210. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  37211. var data = seriesModel.getData();
  37212. var labelLayoutList = [];
  37213. var cx;
  37214. var cy;
  37215. var hasLabelRotate = false;
  37216. data.each(function (idx) {
  37217. var layout = data.getItemLayout(idx);
  37218. var itemModel = data.getItemModel(idx);
  37219. var labelModel = itemModel.getModel('label');
  37220. // Use position in normal or emphasis
  37221. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  37222. var labelLineModel = itemModel.getModel('labelLine');
  37223. var labelLineLen = labelLineModel.get('length');
  37224. var labelLineLen2 = labelLineModel.get('length2');
  37225. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  37226. var dx = Math.cos(midAngle);
  37227. var dy = Math.sin(midAngle);
  37228. var textX;
  37229. var textY;
  37230. var linePoints;
  37231. var textAlign;
  37232. cx = layout.cx;
  37233. cy = layout.cy;
  37234. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  37235. if (labelPosition === 'center') {
  37236. textX = layout.cx;
  37237. textY = layout.cy;
  37238. textAlign = 'center';
  37239. }
  37240. else {
  37241. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  37242. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  37243. textX = x1 + dx * 3;
  37244. textY = y1 + dy * 3;
  37245. if (!isLabelInside) {
  37246. // For roseType
  37247. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  37248. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  37249. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  37250. var y3 = y2;
  37251. textX = x3 + (dx < 0 ? -5 : 5);
  37252. textY = y3;
  37253. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  37254. }
  37255. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  37256. }
  37257. var font = labelModel.getFont();
  37258. var labelRotate = labelModel.get('rotate')
  37259. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  37260. var text = seriesModel.getFormattedLabel(idx, 'normal')
  37261. || data.getName(idx);
  37262. var textRect = getBoundingRect(
  37263. text, font, textAlign, 'top'
  37264. );
  37265. hasLabelRotate = !!labelRotate;
  37266. layout.label = {
  37267. x: textX,
  37268. y: textY,
  37269. position: labelPosition,
  37270. height: textRect.height,
  37271. len: labelLineLen,
  37272. len2: labelLineLen2,
  37273. linePoints: linePoints,
  37274. textAlign: textAlign,
  37275. verticalAlign: 'middle',
  37276. rotation: labelRotate,
  37277. inside: isLabelInside
  37278. };
  37279. // Not layout the inside label
  37280. if (!isLabelInside) {
  37281. labelLayoutList.push(layout.label);
  37282. }
  37283. });
  37284. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  37285. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  37286. }
  37287. };
  37288. /*
  37289. * Licensed to the Apache Software Foundation (ASF) under one
  37290. * or more contributor license agreements. See the NOTICE file
  37291. * distributed with this work for additional information
  37292. * regarding copyright ownership. The ASF licenses this file
  37293. * to you under the Apache License, Version 2.0 (the
  37294. * "License"); you may not use this file except in compliance
  37295. * with the License. You may obtain a copy of the License at
  37296. *
  37297. * http://www.apache.org/licenses/LICENSE-2.0
  37298. *
  37299. * Unless required by applicable law or agreed to in writing,
  37300. * software distributed under the License is distributed on an
  37301. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37302. * KIND, either express or implied. See the License for the
  37303. * specific language governing permissions and limitations
  37304. * under the License.
  37305. */
  37306. var PI2$4 = Math.PI * 2;
  37307. var RADIAN = Math.PI / 180;
  37308. var pieLayout = function (seriesType, ecModel, api, payload) {
  37309. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  37310. var data = seriesModel.getData();
  37311. var valueDim = data.mapDimension('value');
  37312. var center = seriesModel.get('center');
  37313. var radius = seriesModel.get('radius');
  37314. if (!isArray(radius)) {
  37315. radius = [0, radius];
  37316. }
  37317. if (!isArray(center)) {
  37318. center = [center, center];
  37319. }
  37320. var width = api.getWidth();
  37321. var height = api.getHeight();
  37322. var size = Math.min(width, height);
  37323. var cx = parsePercent$1(center[0], width);
  37324. var cy = parsePercent$1(center[1], height);
  37325. var r0 = parsePercent$1(radius[0], size / 2);
  37326. var r = parsePercent$1(radius[1], size / 2);
  37327. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  37328. var minAngle = seriesModel.get('minAngle') * RADIAN;
  37329. var validDataCount = 0;
  37330. data.each(valueDim, function (value) {
  37331. !isNaN(value) && validDataCount++;
  37332. });
  37333. var sum = data.getSum(valueDim);
  37334. // Sum may be 0
  37335. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  37336. var clockwise = seriesModel.get('clockwise');
  37337. var roseType = seriesModel.get('roseType');
  37338. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  37339. // [0...max]
  37340. var extent = data.getDataExtent(valueDim);
  37341. extent[0] = 0;
  37342. // In the case some sector angle is smaller than minAngle
  37343. var restAngle = PI2$4;
  37344. var valueSumLargerThanMinAngle = 0;
  37345. var currentAngle = startAngle;
  37346. var dir = clockwise ? 1 : -1;
  37347. data.each(valueDim, function (value, idx) {
  37348. var angle;
  37349. if (isNaN(value)) {
  37350. data.setItemLayout(idx, {
  37351. angle: NaN,
  37352. startAngle: NaN,
  37353. endAngle: NaN,
  37354. clockwise: clockwise,
  37355. cx: cx,
  37356. cy: cy,
  37357. r0: r0,
  37358. r: roseType
  37359. ? NaN
  37360. : r
  37361. });
  37362. return;
  37363. }
  37364. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  37365. if (roseType !== 'area') {
  37366. angle = (sum === 0 && stillShowZeroSum)
  37367. ? unitRadian : (value * unitRadian);
  37368. }
  37369. else {
  37370. angle = PI2$4 / validDataCount;
  37371. }
  37372. if (angle < minAngle) {
  37373. angle = minAngle;
  37374. restAngle -= minAngle;
  37375. }
  37376. else {
  37377. valueSumLargerThanMinAngle += value;
  37378. }
  37379. var endAngle = currentAngle + dir * angle;
  37380. data.setItemLayout(idx, {
  37381. angle: angle,
  37382. startAngle: currentAngle,
  37383. endAngle: endAngle,
  37384. clockwise: clockwise,
  37385. cx: cx,
  37386. cy: cy,
  37387. r0: r0,
  37388. r: roseType
  37389. ? linearMap(value, extent, [r0, r])
  37390. : r
  37391. });
  37392. currentAngle = endAngle;
  37393. });
  37394. // Some sector is constrained by minAngle
  37395. // Rest sectors needs recalculate angle
  37396. if (restAngle < PI2$4 && validDataCount) {
  37397. // Average the angle if rest angle is not enough after all angles is
  37398. // Constrained by minAngle
  37399. if (restAngle <= 1e-3) {
  37400. var angle = PI2$4 / validDataCount;
  37401. data.each(valueDim, function (value, idx) {
  37402. if (!isNaN(value)) {
  37403. var layout = data.getItemLayout(idx);
  37404. layout.angle = angle;
  37405. layout.startAngle = startAngle + dir * idx * angle;
  37406. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  37407. }
  37408. });
  37409. }
  37410. else {
  37411. unitRadian = restAngle / valueSumLargerThanMinAngle;
  37412. currentAngle = startAngle;
  37413. data.each(valueDim, function (value, idx) {
  37414. if (!isNaN(value)) {
  37415. var layout = data.getItemLayout(idx);
  37416. var angle = layout.angle === minAngle
  37417. ? minAngle : value * unitRadian;
  37418. layout.startAngle = currentAngle;
  37419. layout.endAngle = currentAngle + dir * angle;
  37420. currentAngle += dir * angle;
  37421. }
  37422. });
  37423. }
  37424. }
  37425. labelLayout(seriesModel, r, width, height);
  37426. });
  37427. };
  37428. /*
  37429. * Licensed to the Apache Software Foundation (ASF) under one
  37430. * or more contributor license agreements. See the NOTICE file
  37431. * distributed with this work for additional information
  37432. * regarding copyright ownership. The ASF licenses this file
  37433. * to you under the Apache License, Version 2.0 (the
  37434. * "License"); you may not use this file except in compliance
  37435. * with the License. You may obtain a copy of the License at
  37436. *
  37437. * http://www.apache.org/licenses/LICENSE-2.0
  37438. *
  37439. * Unless required by applicable law or agreed to in writing,
  37440. * software distributed under the License is distributed on an
  37441. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37442. * KIND, either express or implied. See the License for the
  37443. * specific language governing permissions and limitations
  37444. * under the License.
  37445. */
  37446. var dataFilter = function (seriesType) {
  37447. return {
  37448. seriesType: seriesType,
  37449. reset: function (seriesModel, ecModel) {
  37450. var legendModels = ecModel.findComponents({
  37451. mainType: 'legend'
  37452. });
  37453. if (!legendModels || !legendModels.length) {
  37454. return;
  37455. }
  37456. var data = seriesModel.getData();
  37457. data.filterSelf(function (idx) {
  37458. var name = data.getName(idx);
  37459. // If in any legend component the status is not selected.
  37460. for (var i = 0; i < legendModels.length; i++) {
  37461. if (!legendModels[i].isSelected(name)) {
  37462. return false;
  37463. }
  37464. }
  37465. return true;
  37466. });
  37467. }
  37468. };
  37469. };
  37470. /*
  37471. * Licensed to the Apache Software Foundation (ASF) under one
  37472. * or more contributor license agreements. See the NOTICE file
  37473. * distributed with this work for additional information
  37474. * regarding copyright ownership. The ASF licenses this file
  37475. * to you under the Apache License, Version 2.0 (the
  37476. * "License"); you may not use this file except in compliance
  37477. * with the License. You may obtain a copy of the License at
  37478. *
  37479. * http://www.apache.org/licenses/LICENSE-2.0
  37480. *
  37481. * Unless required by applicable law or agreed to in writing,
  37482. * software distributed under the License is distributed on an
  37483. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37484. * KIND, either express or implied. See the License for the
  37485. * specific language governing permissions and limitations
  37486. * under the License.
  37487. */
  37488. createDataSelectAction('pie', [{
  37489. type: 'pieToggleSelect',
  37490. event: 'pieselectchanged',
  37491. method: 'toggleSelected'
  37492. }, {
  37493. type: 'pieSelect',
  37494. event: 'pieselected',
  37495. method: 'select'
  37496. }, {
  37497. type: 'pieUnSelect',
  37498. event: 'pieunselected',
  37499. method: 'unSelect'
  37500. }]);
  37501. registerVisual(dataColor('pie'));
  37502. registerLayout(curry(pieLayout, 'pie'));
  37503. registerProcessor(dataFilter('pie'));
  37504. /*
  37505. * Licensed to the Apache Software Foundation (ASF) under one
  37506. * or more contributor license agreements. See the NOTICE file
  37507. * distributed with this work for additional information
  37508. * regarding copyright ownership. The ASF licenses this file
  37509. * to you under the Apache License, Version 2.0 (the
  37510. * "License"); you may not use this file except in compliance
  37511. * with the License. You may obtain a copy of the License at
  37512. *
  37513. * http://www.apache.org/licenses/LICENSE-2.0
  37514. *
  37515. * Unless required by applicable law or agreed to in writing,
  37516. * software distributed under the License is distributed on an
  37517. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37518. * KIND, either express or implied. See the License for the
  37519. * specific language governing permissions and limitations
  37520. * under the License.
  37521. */
  37522. SeriesModel.extend({
  37523. type: 'series.scatter',
  37524. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  37525. getInitialData: function (option, ecModel) {
  37526. return createListFromArray(this.getSource(), this);
  37527. },
  37528. brushSelector: 'point',
  37529. getProgressive: function () {
  37530. var progressive = this.option.progressive;
  37531. if (progressive == null) {
  37532. // PENDING
  37533. return this.option.large ? 5e3 : this.get('progressive');
  37534. }
  37535. return progressive;
  37536. },
  37537. getProgressiveThreshold: function () {
  37538. var progressiveThreshold = this.option.progressiveThreshold;
  37539. if (progressiveThreshold == null) {
  37540. // PENDING
  37541. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  37542. }
  37543. return progressiveThreshold;
  37544. },
  37545. defaultOption: {
  37546. coordinateSystem: 'cartesian2d',
  37547. zlevel: 0,
  37548. z: 2,
  37549. legendHoverLink: true,
  37550. hoverAnimation: true,
  37551. // Cartesian coordinate system
  37552. // xAxisIndex: 0,
  37553. // yAxisIndex: 0,
  37554. // Polar coordinate system
  37555. // polarIndex: 0,
  37556. // Geo coordinate system
  37557. // geoIndex: 0,
  37558. // symbol: null, // 图形类型
  37559. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  37560. // symbolRotate: null, // 图形旋转控制
  37561. large: false,
  37562. // Available when large is true
  37563. largeThreshold: 2000,
  37564. // cursor: null,
  37565. // label: {
  37566. // show: false
  37567. // distance: 5,
  37568. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  37569. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  37570. // 'inside'|'left'|'right'|'top'|'bottom'
  37571. // 默认使用全局文本样式,详见TEXTSTYLE
  37572. // },
  37573. itemStyle: {
  37574. opacity: 0.8
  37575. // color: 各异
  37576. }
  37577. // progressive: null
  37578. }
  37579. });
  37580. /*
  37581. * Licensed to the Apache Software Foundation (ASF) under one
  37582. * or more contributor license agreements. See the NOTICE file
  37583. * distributed with this work for additional information
  37584. * regarding copyright ownership. The ASF licenses this file
  37585. * to you under the Apache License, Version 2.0 (the
  37586. * "License"); you may not use this file except in compliance
  37587. * with the License. You may obtain a copy of the License at
  37588. *
  37589. * http://www.apache.org/licenses/LICENSE-2.0
  37590. *
  37591. * Unless required by applicable law or agreed to in writing,
  37592. * software distributed under the License is distributed on an
  37593. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37594. * KIND, either express or implied. See the License for the
  37595. * specific language governing permissions and limitations
  37596. * under the License.
  37597. */
  37598. /* global Float32Array */
  37599. // TODO Batch by color
  37600. var BOOST_SIZE_THRESHOLD = 4;
  37601. var LargeSymbolPath = extendShape({
  37602. shape: {
  37603. points: null
  37604. },
  37605. symbolProxy: null,
  37606. buildPath: function (path, shape) {
  37607. var points = shape.points;
  37608. var size = shape.size;
  37609. var symbolProxy = this.symbolProxy;
  37610. var symbolProxyShape = symbolProxy.shape;
  37611. var ctx = path.getContext ? path.getContext() : path;
  37612. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  37613. // Do draw in afterBrush.
  37614. if (canBoost) {
  37615. return;
  37616. }
  37617. for (var i = 0; i < points.length;) {
  37618. var x = points[i++];
  37619. var y = points[i++];
  37620. if (isNaN(x) || isNaN(y)) {
  37621. continue;
  37622. }
  37623. symbolProxyShape.x = x - size[0] / 2;
  37624. symbolProxyShape.y = y - size[1] / 2;
  37625. symbolProxyShape.width = size[0];
  37626. symbolProxyShape.height = size[1];
  37627. symbolProxy.buildPath(path, symbolProxyShape, true);
  37628. }
  37629. },
  37630. afterBrush: function (ctx) {
  37631. var shape = this.shape;
  37632. var points = shape.points;
  37633. var size = shape.size;
  37634. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  37635. if (!canBoost) {
  37636. return;
  37637. }
  37638. this.setTransform(ctx);
  37639. // PENDING If style or other canvas status changed?
  37640. for (var i = 0; i < points.length;) {
  37641. var x = points[i++];
  37642. var y = points[i++];
  37643. if (isNaN(x) || isNaN(y)) {
  37644. continue;
  37645. }
  37646. // fillRect is faster than building a rect path and draw.
  37647. // And it support light globalCompositeOperation.
  37648. ctx.fillRect(
  37649. x - size[0] / 2, y - size[1] / 2,
  37650. size[0], size[1]
  37651. );
  37652. }
  37653. this.restoreTransform(ctx);
  37654. },
  37655. findDataIndex: function (x, y) {
  37656. // TODO ???
  37657. // Consider transform
  37658. var shape = this.shape;
  37659. var points = shape.points;
  37660. var size = shape.size;
  37661. var w = Math.max(size[0], 4);
  37662. var h = Math.max(size[1], 4);
  37663. // Not consider transform
  37664. // Treat each element as a rect
  37665. // top down traverse
  37666. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  37667. var i = idx * 2;
  37668. var x0 = points[i] - w / 2;
  37669. var y0 = points[i + 1] - h / 2;
  37670. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  37671. return idx;
  37672. }
  37673. }
  37674. return -1;
  37675. }
  37676. });
  37677. function LargeSymbolDraw() {
  37678. this.group = new Group();
  37679. }
  37680. var largeSymbolProto = LargeSymbolDraw.prototype;
  37681. largeSymbolProto.isPersistent = function () {
  37682. return !this._incremental;
  37683. };
  37684. /**
  37685. * Update symbols draw by new data
  37686. * @param {module:echarts/data/List} data
  37687. */
  37688. largeSymbolProto.updateData = function (data) {
  37689. this.group.removeAll();
  37690. var symbolEl = new LargeSymbolPath({
  37691. rectHover: true,
  37692. cursor: 'default'
  37693. });
  37694. symbolEl.setShape({
  37695. points: data.getLayout('symbolPoints')
  37696. });
  37697. this._setCommon(symbolEl, data);
  37698. this.group.add(symbolEl);
  37699. this._incremental = null;
  37700. };
  37701. largeSymbolProto.updateLayout = function (data) {
  37702. if (this._incremental) {
  37703. return;
  37704. }
  37705. var points = data.getLayout('symbolPoints');
  37706. this.group.eachChild(function (child) {
  37707. if (child.startIndex != null) {
  37708. var len = (child.endIndex - child.startIndex) * 2;
  37709. var byteOffset = child.startIndex * 4 * 2;
  37710. points = new Float32Array(points.buffer, byteOffset, len);
  37711. }
  37712. child.setShape('points', points);
  37713. });
  37714. };
  37715. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  37716. this.group.removeAll();
  37717. this._clearIncremental();
  37718. // Only use incremental displayables when data amount is larger than 2 million.
  37719. // PENDING Incremental data?
  37720. if (data.count() > 2e6) {
  37721. if (!this._incremental) {
  37722. this._incremental = new IncrementalDisplayble({
  37723. silent: true
  37724. });
  37725. }
  37726. this.group.add(this._incremental);
  37727. }
  37728. else {
  37729. this._incremental = null;
  37730. }
  37731. };
  37732. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  37733. var symbolEl;
  37734. if (this._incremental) {
  37735. symbolEl = new LargeSymbolPath();
  37736. this._incremental.addDisplayable(symbolEl, true);
  37737. }
  37738. else {
  37739. symbolEl = new LargeSymbolPath({
  37740. rectHover: true,
  37741. cursor: 'default',
  37742. startIndex: taskParams.start,
  37743. endIndex: taskParams.end
  37744. });
  37745. symbolEl.incremental = true;
  37746. this.group.add(symbolEl);
  37747. }
  37748. symbolEl.setShape({
  37749. points: data.getLayout('symbolPoints')
  37750. });
  37751. this._setCommon(symbolEl, data, !!this._incremental);
  37752. };
  37753. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  37754. var hostModel = data.hostModel;
  37755. // TODO
  37756. // if (data.hasItemVisual.symbolSize) {
  37757. // // TODO typed array?
  37758. // symbolEl.setShape('sizes', data.mapArray(
  37759. // function (idx) {
  37760. // var size = data.getItemVisual(idx, 'symbolSize');
  37761. // return (size instanceof Array) ? size : [size, size];
  37762. // }
  37763. // ));
  37764. // }
  37765. // else {
  37766. var size = data.getVisual('symbolSize');
  37767. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  37768. // }
  37769. // Create symbolProxy to build path for each data
  37770. symbolEl.symbolProxy = createSymbol(
  37771. data.getVisual('symbol'), 0, 0, 0, 0
  37772. );
  37773. // Use symbolProxy setColor method
  37774. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  37775. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  37776. symbolEl.useStyle(
  37777. // Draw shadow when doing fillRect is extremely slow.
  37778. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  37779. );
  37780. var visualColor = data.getVisual('color');
  37781. if (visualColor) {
  37782. symbolEl.setColor(visualColor);
  37783. }
  37784. if (!isIncremental) {
  37785. // Enable tooltip
  37786. // PENDING May have performance issue when path is extremely large
  37787. symbolEl.seriesIndex = hostModel.seriesIndex;
  37788. symbolEl.on('mousemove', function (e) {
  37789. symbolEl.dataIndex = null;
  37790. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  37791. if (dataIndex >= 0) {
  37792. // Provide dataIndex for tooltip
  37793. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  37794. }
  37795. });
  37796. }
  37797. };
  37798. largeSymbolProto.remove = function () {
  37799. this._clearIncremental();
  37800. this._incremental = null;
  37801. this.group.removeAll();
  37802. };
  37803. largeSymbolProto._clearIncremental = function () {
  37804. var incremental = this._incremental;
  37805. if (incremental) {
  37806. incremental.clearDisplaybles();
  37807. }
  37808. };
  37809. /*
  37810. * Licensed to the Apache Software Foundation (ASF) under one
  37811. * or more contributor license agreements. See the NOTICE file
  37812. * distributed with this work for additional information
  37813. * regarding copyright ownership. The ASF licenses this file
  37814. * to you under the Apache License, Version 2.0 (the
  37815. * "License"); you may not use this file except in compliance
  37816. * with the License. You may obtain a copy of the License at
  37817. *
  37818. * http://www.apache.org/licenses/LICENSE-2.0
  37819. *
  37820. * Unless required by applicable law or agreed to in writing,
  37821. * software distributed under the License is distributed on an
  37822. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37823. * KIND, either express or implied. See the License for the
  37824. * specific language governing permissions and limitations
  37825. * under the License.
  37826. */
  37827. extendChartView({
  37828. type: 'scatter',
  37829. render: function (seriesModel, ecModel, api) {
  37830. var data = seriesModel.getData();
  37831. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  37832. symbolDraw.updateData(data);
  37833. this._finished = true;
  37834. },
  37835. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  37836. var data = seriesModel.getData();
  37837. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  37838. symbolDraw.incrementalPrepareUpdate(data);
  37839. this._finished = false;
  37840. },
  37841. incrementalRender: function (taskParams, seriesModel, ecModel) {
  37842. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  37843. this._finished = taskParams.end === seriesModel.getData().count();
  37844. },
  37845. updateTransform: function (seriesModel, ecModel, api) {
  37846. var data = seriesModel.getData();
  37847. // Must mark group dirty and make sure the incremental layer will be cleared
  37848. // PENDING
  37849. this.group.dirty();
  37850. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  37851. return {
  37852. update: true
  37853. };
  37854. }
  37855. else {
  37856. var res = pointsLayout().reset(seriesModel);
  37857. if (res.progress) {
  37858. res.progress({ start: 0, end: data.count() }, data);
  37859. }
  37860. this._symbolDraw.updateLayout(data);
  37861. }
  37862. },
  37863. _updateSymbolDraw: function (data, seriesModel) {
  37864. var symbolDraw = this._symbolDraw;
  37865. var pipelineContext = seriesModel.pipelineContext;
  37866. var isLargeDraw = pipelineContext.large;
  37867. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  37868. symbolDraw && symbolDraw.remove();
  37869. symbolDraw = this._symbolDraw = isLargeDraw
  37870. ? new LargeSymbolDraw()
  37871. : new SymbolDraw();
  37872. this._isLargeDraw = isLargeDraw;
  37873. this.group.removeAll();
  37874. }
  37875. this.group.add(symbolDraw.group);
  37876. return symbolDraw;
  37877. },
  37878. remove: function (ecModel, api) {
  37879. this._symbolDraw && this._symbolDraw.remove(true);
  37880. this._symbolDraw = null;
  37881. },
  37882. dispose: function () {}
  37883. });
  37884. /*
  37885. * Licensed to the Apache Software Foundation (ASF) under one
  37886. * or more contributor license agreements. See the NOTICE file
  37887. * distributed with this work for additional information
  37888. * regarding copyright ownership. The ASF licenses this file
  37889. * to you under the Apache License, Version 2.0 (the
  37890. * "License"); you may not use this file except in compliance
  37891. * with the License. You may obtain a copy of the License at
  37892. *
  37893. * http://www.apache.org/licenses/LICENSE-2.0
  37894. *
  37895. * Unless required by applicable law or agreed to in writing,
  37896. * software distributed under the License is distributed on an
  37897. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37898. * KIND, either express or implied. See the License for the
  37899. * specific language governing permissions and limitations
  37900. * under the License.
  37901. */
  37902. // import * as zrUtil from 'zrender/src/core/util';
  37903. // In case developer forget to include grid component
  37904. registerVisual(visualSymbol('scatter', 'circle'));
  37905. registerLayout(pointsLayout('scatter'));
  37906. // echarts.registerProcessor(function (ecModel, api) {
  37907. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  37908. // var data = seriesModel.getData();
  37909. // var coordSys = seriesModel.coordinateSystem;
  37910. // if (coordSys.type !== 'geo') {
  37911. // return;
  37912. // }
  37913. // var startPt = coordSys.pointToData([0, 0]);
  37914. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  37915. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  37916. // return data.mapDimension(dim);
  37917. // });
  37918. // var range = {};
  37919. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  37920. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  37921. // data.selectRange(range);
  37922. // });
  37923. // });
  37924. /*
  37925. * Licensed to the Apache Software Foundation (ASF) under one
  37926. * or more contributor license agreements. See the NOTICE file
  37927. * distributed with this work for additional information
  37928. * regarding copyright ownership. The ASF licenses this file
  37929. * to you under the Apache License, Version 2.0 (the
  37930. * "License"); you may not use this file except in compliance
  37931. * with the License. You may obtain a copy of the License at
  37932. *
  37933. * http://www.apache.org/licenses/LICENSE-2.0
  37934. *
  37935. * Unless required by applicable law or agreed to in writing,
  37936. * software distributed under the License is distributed on an
  37937. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37938. * KIND, either express or implied. See the License for the
  37939. * specific language governing permissions and limitations
  37940. * under the License.
  37941. */
  37942. function IndicatorAxis(dim, scale, radiusExtent) {
  37943. Axis.call(this, dim, scale, radiusExtent);
  37944. /**
  37945. * Axis type
  37946. * - 'category'
  37947. * - 'value'
  37948. * - 'time'
  37949. * - 'log'
  37950. * @type {string}
  37951. */
  37952. this.type = 'value';
  37953. this.angle = 0;
  37954. /**
  37955. * Indicator name
  37956. * @type {string}
  37957. */
  37958. this.name = '';
  37959. /**
  37960. * @type {module:echarts/model/Model}
  37961. */
  37962. this.model;
  37963. }
  37964. inherits(IndicatorAxis, Axis);
  37965. /*
  37966. * Licensed to the Apache Software Foundation (ASF) under one
  37967. * or more contributor license agreements. See the NOTICE file
  37968. * distributed with this work for additional information
  37969. * regarding copyright ownership. The ASF licenses this file
  37970. * to you under the Apache License, Version 2.0 (the
  37971. * "License"); you may not use this file except in compliance
  37972. * with the License. You may obtain a copy of the License at
  37973. *
  37974. * http://www.apache.org/licenses/LICENSE-2.0
  37975. *
  37976. * Unless required by applicable law or agreed to in writing,
  37977. * software distributed under the License is distributed on an
  37978. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37979. * KIND, either express or implied. See the License for the
  37980. * specific language governing permissions and limitations
  37981. * under the License.
  37982. */
  37983. // TODO clockwise
  37984. function Radar(radarModel, ecModel, api) {
  37985. this._model = radarModel;
  37986. /**
  37987. * Radar dimensions
  37988. * @type {Array.<string>}
  37989. */
  37990. this.dimensions = [];
  37991. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  37992. var dim = 'indicator_' + idx;
  37993. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale());
  37994. indicatorAxis.name = indicatorModel.get('name');
  37995. // Inject model and axis
  37996. indicatorAxis.model = indicatorModel;
  37997. indicatorModel.axis = indicatorAxis;
  37998. this.dimensions.push(dim);
  37999. return indicatorAxis;
  38000. }, this);
  38001. this.resize(radarModel, api);
  38002. /**
  38003. * @type {number}
  38004. * @readOnly
  38005. */
  38006. this.cx;
  38007. /**
  38008. * @type {number}
  38009. * @readOnly
  38010. */
  38011. this.cy;
  38012. /**
  38013. * @type {number}
  38014. * @readOnly
  38015. */
  38016. this.r;
  38017. /**
  38018. * @type {number}
  38019. * @readOnly
  38020. */
  38021. this.r0;
  38022. /**
  38023. * @type {number}
  38024. * @readOnly
  38025. */
  38026. this.startAngle;
  38027. }
  38028. Radar.prototype.getIndicatorAxes = function () {
  38029. return this._indicatorAxes;
  38030. };
  38031. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  38032. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  38033. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  38034. };
  38035. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  38036. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  38037. var angle = indicatorAxis.angle;
  38038. var x = this.cx + coord * Math.cos(angle);
  38039. var y = this.cy - coord * Math.sin(angle);
  38040. return [x, y];
  38041. };
  38042. Radar.prototype.pointToData = function (pt) {
  38043. var dx = pt[0] - this.cx;
  38044. var dy = pt[1] - this.cy;
  38045. var radius = Math.sqrt(dx * dx + dy * dy);
  38046. dx /= radius;
  38047. dy /= radius;
  38048. var radian = Math.atan2(-dy, dx);
  38049. // Find the closest angle
  38050. // FIXME index can calculated directly
  38051. var minRadianDiff = Infinity;
  38052. var closestAxis;
  38053. var closestAxisIdx = -1;
  38054. for (var i = 0; i < this._indicatorAxes.length; i++) {
  38055. var indicatorAxis = this._indicatorAxes[i];
  38056. var diff = Math.abs(radian - indicatorAxis.angle);
  38057. if (diff < minRadianDiff) {
  38058. closestAxis = indicatorAxis;
  38059. closestAxisIdx = i;
  38060. minRadianDiff = diff;
  38061. }
  38062. }
  38063. return [closestAxisIdx, +(closestAxis && closestAxis.coodToData(radius))];
  38064. };
  38065. Radar.prototype.resize = function (radarModel, api) {
  38066. var center = radarModel.get('center');
  38067. var viewWidth = api.getWidth();
  38068. var viewHeight = api.getHeight();
  38069. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  38070. this.cx = parsePercent$1(center[0], viewWidth);
  38071. this.cy = parsePercent$1(center[1], viewHeight);
  38072. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  38073. // radius may be single value like `20`, `'80%'`, or array like `[10, '80%']`
  38074. var radius = radarModel.get('radius');
  38075. if (typeof radius === 'string' || typeof radius === 'number') {
  38076. radius = [0, radius];
  38077. }
  38078. this.r0 = parsePercent$1(radius[0], viewSize);
  38079. this.r = parsePercent$1(radius[1], viewSize);
  38080. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  38081. indicatorAxis.setExtent(this.r0, this.r);
  38082. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  38083. // Normalize to [-PI, PI]
  38084. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  38085. indicatorAxis.angle = angle;
  38086. }, this);
  38087. };
  38088. Radar.prototype.update = function (ecModel, api) {
  38089. var indicatorAxes = this._indicatorAxes;
  38090. var radarModel = this._model;
  38091. each$1(indicatorAxes, function (indicatorAxis) {
  38092. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  38093. });
  38094. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  38095. if (radarSeries.get('coordinateSystem') !== 'radar'
  38096. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  38097. ) {
  38098. return;
  38099. }
  38100. var data = radarSeries.getData();
  38101. each$1(indicatorAxes, function (indicatorAxis) {
  38102. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  38103. });
  38104. }, this);
  38105. var splitNumber = radarModel.get('splitNumber');
  38106. function increaseInterval(interval) {
  38107. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  38108. // Increase interval
  38109. var f = interval / exp10;
  38110. if (f === 2) {
  38111. f = 5;
  38112. }
  38113. else { // f is 2 or 5
  38114. f *= 2;
  38115. }
  38116. return f * exp10;
  38117. }
  38118. // Force all the axis fixing the maxSplitNumber.
  38119. each$1(indicatorAxes, function (indicatorAxis, idx) {
  38120. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  38121. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  38122. var axisModel = indicatorAxis.model;
  38123. var scale = indicatorAxis.scale;
  38124. var fixedMin = axisModel.getMin();
  38125. var fixedMax = axisModel.getMax();
  38126. var interval = scale.getInterval();
  38127. if (fixedMin != null && fixedMax != null) {
  38128. // User set min, max, divide to get new interval
  38129. scale.setExtent(+fixedMin, +fixedMax);
  38130. scale.setInterval(
  38131. (fixedMax - fixedMin) / splitNumber
  38132. );
  38133. }
  38134. else if (fixedMin != null) {
  38135. var max;
  38136. // User set min, expand extent on the other side
  38137. do {
  38138. max = fixedMin + interval * splitNumber;
  38139. scale.setExtent(+fixedMin, max);
  38140. // Interval must been set after extent
  38141. // FIXME
  38142. scale.setInterval(interval);
  38143. interval = increaseInterval(interval);
  38144. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  38145. }
  38146. else if (fixedMax != null) {
  38147. var min;
  38148. // User set min, expand extent on the other side
  38149. do {
  38150. min = fixedMax - interval * splitNumber;
  38151. scale.setExtent(min, +fixedMax);
  38152. scale.setInterval(interval);
  38153. interval = increaseInterval(interval);
  38154. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  38155. }
  38156. else {
  38157. var nicedSplitNumber = scale.getTicks().length - 1;
  38158. if (nicedSplitNumber > splitNumber) {
  38159. interval = increaseInterval(interval);
  38160. }
  38161. // PENDING
  38162. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  38163. var halfSplitNumber = Math.round(splitNumber / 2);
  38164. scale.setExtent(
  38165. round$2(center - halfSplitNumber * interval),
  38166. round$2(center + (splitNumber - halfSplitNumber) * interval)
  38167. );
  38168. scale.setInterval(interval);
  38169. }
  38170. });
  38171. };
  38172. /**
  38173. * Radar dimensions is based on the data
  38174. * @type {Array}
  38175. */
  38176. Radar.dimensions = [];
  38177. Radar.create = function (ecModel, api) {
  38178. var radarList = [];
  38179. ecModel.eachComponent('radar', function (radarModel) {
  38180. var radar = new Radar(radarModel, ecModel, api);
  38181. radarList.push(radar);
  38182. radarModel.coordinateSystem = radar;
  38183. });
  38184. ecModel.eachSeriesByType('radar', function (radarSeries) {
  38185. if (radarSeries.get('coordinateSystem') === 'radar') {
  38186. // Inject coordinate system
  38187. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  38188. }
  38189. });
  38190. return radarList;
  38191. };
  38192. CoordinateSystemManager.register('radar', Radar);
  38193. /*
  38194. * Licensed to the Apache Software Foundation (ASF) under one
  38195. * or more contributor license agreements. See the NOTICE file
  38196. * distributed with this work for additional information
  38197. * regarding copyright ownership. The ASF licenses this file
  38198. * to you under the Apache License, Version 2.0 (the
  38199. * "License"); you may not use this file except in compliance
  38200. * with the License. You may obtain a copy of the License at
  38201. *
  38202. * http://www.apache.org/licenses/LICENSE-2.0
  38203. *
  38204. * Unless required by applicable law or agreed to in writing,
  38205. * software distributed under the License is distributed on an
  38206. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38207. * KIND, either express or implied. See the License for the
  38208. * specific language governing permissions and limitations
  38209. * under the License.
  38210. */
  38211. var valueAxisDefault = axisDefault.valueAxis;
  38212. function defaultsShow(opt, show) {
  38213. return defaults({
  38214. show: show
  38215. }, opt);
  38216. }
  38217. var RadarModel = extendComponentModel({
  38218. type: 'radar',
  38219. optionUpdated: function () {
  38220. var boundaryGap = this.get('boundaryGap');
  38221. var splitNumber = this.get('splitNumber');
  38222. var scale = this.get('scale');
  38223. var axisLine = this.get('axisLine');
  38224. var axisTick = this.get('axisTick');
  38225. var axisLabel = this.get('axisLabel');
  38226. var nameTextStyle = this.get('name');
  38227. var showName = this.get('name.show');
  38228. var nameFormatter = this.get('name.formatter');
  38229. var nameGap = this.get('nameGap');
  38230. var triggerEvent = this.get('triggerEvent');
  38231. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  38232. // PENDING
  38233. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  38234. indicatorOpt.min = 0;
  38235. }
  38236. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  38237. indicatorOpt.max = 0;
  38238. }
  38239. var iNameTextStyle = nameTextStyle;
  38240. if (indicatorOpt.color != null) {
  38241. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  38242. }
  38243. // Use same configuration
  38244. indicatorOpt = merge(clone(indicatorOpt), {
  38245. boundaryGap: boundaryGap,
  38246. splitNumber: splitNumber,
  38247. scale: scale,
  38248. axisLine: axisLine,
  38249. axisTick: axisTick,
  38250. axisLabel: axisLabel,
  38251. // Competitable with 2 and use text
  38252. name: indicatorOpt.text,
  38253. nameLocation: 'end',
  38254. nameGap: nameGap,
  38255. // min: 0,
  38256. nameTextStyle: iNameTextStyle,
  38257. triggerEvent: triggerEvent
  38258. }, false);
  38259. if (!showName) {
  38260. indicatorOpt.name = '';
  38261. }
  38262. if (typeof nameFormatter === 'string') {
  38263. var indName = indicatorOpt.name;
  38264. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  38265. }
  38266. else if (typeof nameFormatter === 'function') {
  38267. indicatorOpt.name = nameFormatter(
  38268. indicatorOpt.name, indicatorOpt
  38269. );
  38270. }
  38271. var model = extend(
  38272. new Model(indicatorOpt, null, this.ecModel),
  38273. axisModelCommonMixin
  38274. );
  38275. // For triggerEvent.
  38276. model.mainType = 'radar';
  38277. model.componentIndex = this.componentIndex;
  38278. return model;
  38279. }, this);
  38280. this.getIndicatorModels = function () {
  38281. return indicatorModels;
  38282. };
  38283. },
  38284. defaultOption: {
  38285. zlevel: 0,
  38286. z: 0,
  38287. center: ['50%', '50%'],
  38288. radius: '75%',
  38289. startAngle: 90,
  38290. name: {
  38291. show: true
  38292. // formatter: null
  38293. // textStyle: {}
  38294. },
  38295. boundaryGap: [0, 0],
  38296. splitNumber: 5,
  38297. nameGap: 15,
  38298. scale: false,
  38299. // Polygon or circle
  38300. shape: 'polygon',
  38301. axisLine: merge(
  38302. {
  38303. lineStyle: {
  38304. color: '#bbb'
  38305. }
  38306. },
  38307. valueAxisDefault.axisLine
  38308. ),
  38309. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  38310. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  38311. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  38312. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  38313. // {text, min, max}
  38314. indicator: []
  38315. }
  38316. });
  38317. /*
  38318. * Licensed to the Apache Software Foundation (ASF) under one
  38319. * or more contributor license agreements. See the NOTICE file
  38320. * distributed with this work for additional information
  38321. * regarding copyright ownership. The ASF licenses this file
  38322. * to you under the Apache License, Version 2.0 (the
  38323. * "License"); you may not use this file except in compliance
  38324. * with the License. You may obtain a copy of the License at
  38325. *
  38326. * http://www.apache.org/licenses/LICENSE-2.0
  38327. *
  38328. * Unless required by applicable law or agreed to in writing,
  38329. * software distributed under the License is distributed on an
  38330. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38331. * KIND, either express or implied. See the License for the
  38332. * specific language governing permissions and limitations
  38333. * under the License.
  38334. */
  38335. var axisBuilderAttrs$1 = [
  38336. 'axisLine', 'axisTickLabel', 'axisName'
  38337. ];
  38338. extendComponentView({
  38339. type: 'radar',
  38340. render: function (radarModel, ecModel, api) {
  38341. var group = this.group;
  38342. group.removeAll();
  38343. this._buildAxes(radarModel);
  38344. this._buildSplitLineAndArea(radarModel);
  38345. },
  38346. _buildAxes: function (radarModel) {
  38347. var radar = radarModel.coordinateSystem;
  38348. var indicatorAxes = radar.getIndicatorAxes();
  38349. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  38350. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  38351. position: [radar.cx, radar.cy],
  38352. rotation: indicatorAxis.angle,
  38353. labelDirection: -1,
  38354. tickDirection: -1,
  38355. nameDirection: 1
  38356. });
  38357. return axisBuilder;
  38358. });
  38359. each$1(axisBuilders, function (axisBuilder) {
  38360. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  38361. this.group.add(axisBuilder.getGroup());
  38362. }, this);
  38363. },
  38364. _buildSplitLineAndArea: function (radarModel) {
  38365. var radar = radarModel.coordinateSystem;
  38366. var indicatorAxes = radar.getIndicatorAxes();
  38367. if (!indicatorAxes.length) {
  38368. return;
  38369. }
  38370. var shape = radarModel.get('shape');
  38371. var splitLineModel = radarModel.getModel('splitLine');
  38372. var splitAreaModel = radarModel.getModel('splitArea');
  38373. var lineStyleModel = splitLineModel.getModel('lineStyle');
  38374. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  38375. var showSplitLine = splitLineModel.get('show');
  38376. var showSplitArea = splitAreaModel.get('show');
  38377. var splitLineColors = lineStyleModel.get('color');
  38378. var splitAreaColors = areaStyleModel.get('color');
  38379. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  38380. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  38381. var splitLines = [];
  38382. var splitAreas = [];
  38383. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  38384. var colorIndex = idx % areaOrLineColorList.length;
  38385. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  38386. return colorIndex;
  38387. }
  38388. if (shape === 'circle') {
  38389. var ticksRadius = indicatorAxes[0].getTicksCoords();
  38390. var cx = radar.cx;
  38391. var cy = radar.cy;
  38392. for (var i = 0; i < ticksRadius.length; i++) {
  38393. if (showSplitLine) {
  38394. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  38395. splitLines[colorIndex].push(new Circle({
  38396. shape: {
  38397. cx: cx,
  38398. cy: cy,
  38399. r: ticksRadius[i].coord
  38400. }
  38401. }));
  38402. }
  38403. if (showSplitArea && i < ticksRadius.length - 1) {
  38404. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  38405. splitAreas[colorIndex].push(new Ring({
  38406. shape: {
  38407. cx: cx,
  38408. cy: cy,
  38409. r0: ticksRadius[i].coord,
  38410. r: ticksRadius[i + 1].coord
  38411. }
  38412. }));
  38413. }
  38414. }
  38415. }
  38416. // Polyyon
  38417. else {
  38418. var realSplitNumber;
  38419. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  38420. var ticksCoords = indicatorAxis.getTicksCoords();
  38421. realSplitNumber = realSplitNumber == null
  38422. ? ticksCoords.length - 1
  38423. : Math.min(ticksCoords.length - 1, realSplitNumber);
  38424. return map(ticksCoords, function (tickCoord) {
  38425. return radar.coordToPoint(tickCoord.coord, idx);
  38426. });
  38427. });
  38428. var prevPoints = [];
  38429. for (var i = 0; i <= realSplitNumber; i++) {
  38430. var points = [];
  38431. for (var j = 0; j < indicatorAxes.length; j++) {
  38432. points.push(axesTicksPoints[j][i]);
  38433. }
  38434. // Close
  38435. if (points[0]) {
  38436. points.push(points[0].slice());
  38437. }
  38438. else {
  38439. if (__DEV__) {
  38440. console.error('Can\'t draw value axis ' + i);
  38441. }
  38442. }
  38443. if (showSplitLine) {
  38444. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  38445. splitLines[colorIndex].push(new Polyline({
  38446. shape: {
  38447. points: points
  38448. }
  38449. }));
  38450. }
  38451. if (showSplitArea && prevPoints) {
  38452. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  38453. splitAreas[colorIndex].push(new Polygon({
  38454. shape: {
  38455. points: points.concat(prevPoints)
  38456. }
  38457. }));
  38458. }
  38459. prevPoints = points.slice().reverse();
  38460. }
  38461. }
  38462. var lineStyle = lineStyleModel.getLineStyle();
  38463. var areaStyle = areaStyleModel.getAreaStyle();
  38464. // Add splitArea before splitLine
  38465. each$1(splitAreas, function (splitAreas, idx) {
  38466. this.group.add(mergePath(
  38467. splitAreas, {
  38468. style: defaults({
  38469. stroke: 'none',
  38470. fill: splitAreaColors[idx % splitAreaColors.length]
  38471. }, areaStyle),
  38472. silent: true
  38473. }
  38474. ));
  38475. }, this);
  38476. each$1(splitLines, function (splitLines, idx) {
  38477. this.group.add(mergePath(
  38478. splitLines, {
  38479. style: defaults({
  38480. fill: 'none',
  38481. stroke: splitLineColors[idx % splitLineColors.length]
  38482. }, lineStyle),
  38483. silent: true
  38484. }
  38485. ));
  38486. }, this);
  38487. }
  38488. });
  38489. /*
  38490. * Licensed to the Apache Software Foundation (ASF) under one
  38491. * or more contributor license agreements. See the NOTICE file
  38492. * distributed with this work for additional information
  38493. * regarding copyright ownership. The ASF licenses this file
  38494. * to you under the Apache License, Version 2.0 (the
  38495. * "License"); you may not use this file except in compliance
  38496. * with the License. You may obtain a copy of the License at
  38497. *
  38498. * http://www.apache.org/licenses/LICENSE-2.0
  38499. *
  38500. * Unless required by applicable law or agreed to in writing,
  38501. * software distributed under the License is distributed on an
  38502. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38503. * KIND, either express or implied. See the License for the
  38504. * specific language governing permissions and limitations
  38505. * under the License.
  38506. */
  38507. /*
  38508. * Licensed to the Apache Software Foundation (ASF) under one
  38509. * or more contributor license agreements. See the NOTICE file
  38510. * distributed with this work for additional information
  38511. * regarding copyright ownership. The ASF licenses this file
  38512. * to you under the Apache License, Version 2.0 (the
  38513. * "License"); you may not use this file except in compliance
  38514. * with the License. You may obtain a copy of the License at
  38515. *
  38516. * http://www.apache.org/licenses/LICENSE-2.0
  38517. *
  38518. * Unless required by applicable law or agreed to in writing,
  38519. * software distributed under the License is distributed on an
  38520. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38521. * KIND, either express or implied. See the License for the
  38522. * specific language governing permissions and limitations
  38523. * under the License.
  38524. */
  38525. var RadarSeries = SeriesModel.extend({
  38526. type: 'series.radar',
  38527. dependencies: ['radar'],
  38528. // Overwrite
  38529. init: function (option) {
  38530. RadarSeries.superApply(this, 'init', arguments);
  38531. // Enable legend selection for each data item
  38532. // Use a function instead of direct access because data reference may changed
  38533. this.legendDataProvider = function () {
  38534. return this.getRawData();
  38535. };
  38536. },
  38537. getInitialData: function (option, ecModel) {
  38538. return createListSimply(this, {
  38539. generateCoord: 'indicator_',
  38540. generateCoordCount: Infinity
  38541. });
  38542. },
  38543. formatTooltip: function (dataIndex) {
  38544. var data = this.getData();
  38545. var coordSys = this.coordinateSystem;
  38546. var indicatorAxes = coordSys.getIndicatorAxes();
  38547. var name = this.getData().getName(dataIndex);
  38548. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  38549. + map(indicatorAxes, function (axis, idx) {
  38550. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  38551. return encodeHTML(axis.name + ' : ' + val);
  38552. }).join('<br />');
  38553. },
  38554. defaultOption: {
  38555. zlevel: 0,
  38556. z: 2,
  38557. coordinateSystem: 'radar',
  38558. legendHoverLink: true,
  38559. radarIndex: 0,
  38560. lineStyle: {
  38561. width: 2,
  38562. type: 'solid'
  38563. },
  38564. label: {
  38565. position: 'top'
  38566. },
  38567. // areaStyle: {
  38568. // },
  38569. // itemStyle: {}
  38570. symbol: 'emptyCircle',
  38571. symbolSize: 4
  38572. // symbolRotate: null
  38573. }
  38574. });
  38575. /*
  38576. * Licensed to the Apache Software Foundation (ASF) under one
  38577. * or more contributor license agreements. See the NOTICE file
  38578. * distributed with this work for additional information
  38579. * regarding copyright ownership. The ASF licenses this file
  38580. * to you under the Apache License, Version 2.0 (the
  38581. * "License"); you may not use this file except in compliance
  38582. * with the License. You may obtain a copy of the License at
  38583. *
  38584. * http://www.apache.org/licenses/LICENSE-2.0
  38585. *
  38586. * Unless required by applicable law or agreed to in writing,
  38587. * software distributed under the License is distributed on an
  38588. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38589. * KIND, either express or implied. See the License for the
  38590. * specific language governing permissions and limitations
  38591. * under the License.
  38592. */
  38593. function normalizeSymbolSize(symbolSize) {
  38594. if (!isArray(symbolSize)) {
  38595. symbolSize = [+symbolSize, +symbolSize];
  38596. }
  38597. return symbolSize;
  38598. }
  38599. extendChartView({
  38600. type: 'radar',
  38601. render: function (seriesModel, ecModel, api) {
  38602. var polar = seriesModel.coordinateSystem;
  38603. var group = this.group;
  38604. var data = seriesModel.getData();
  38605. var oldData = this._data;
  38606. function createSymbol$$1(data, idx) {
  38607. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  38608. var color = data.getItemVisual(idx, 'color');
  38609. if (symbolType === 'none') {
  38610. return;
  38611. }
  38612. var symbolSize = normalizeSymbolSize(
  38613. data.getItemVisual(idx, 'symbolSize')
  38614. );
  38615. var symbolPath = createSymbol(
  38616. symbolType, -1, -1, 2, 2, color
  38617. );
  38618. symbolPath.attr({
  38619. style: {
  38620. strokeNoScale: true
  38621. },
  38622. z2: 100,
  38623. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  38624. });
  38625. return symbolPath;
  38626. }
  38627. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  38628. // Simply rerender all
  38629. symbolGroup.removeAll();
  38630. for (var i = 0; i < newPoints.length - 1; i++) {
  38631. var symbolPath = createSymbol$$1(data, idx);
  38632. if (symbolPath) {
  38633. symbolPath.__dimIdx = i;
  38634. if (oldPoints[i]) {
  38635. symbolPath.attr('position', oldPoints[i]);
  38636. graphic[isInit ? 'initProps' : 'updateProps'](
  38637. symbolPath, {
  38638. position: newPoints[i]
  38639. }, seriesModel, idx
  38640. );
  38641. }
  38642. else {
  38643. symbolPath.attr('position', newPoints[i]);
  38644. }
  38645. symbolGroup.add(symbolPath);
  38646. }
  38647. }
  38648. }
  38649. function getInitialPoints(points) {
  38650. return map(points, function (pt) {
  38651. return [polar.cx, polar.cy];
  38652. });
  38653. }
  38654. data.diff(oldData)
  38655. .add(function (idx) {
  38656. var points = data.getItemLayout(idx);
  38657. if (!points) {
  38658. return;
  38659. }
  38660. var polygon = new Polygon();
  38661. var polyline = new Polyline();
  38662. var target = {
  38663. shape: {
  38664. points: points
  38665. }
  38666. };
  38667. polygon.shape.points = getInitialPoints(points);
  38668. polyline.shape.points = getInitialPoints(points);
  38669. initProps(polygon, target, seriesModel, idx);
  38670. initProps(polyline, target, seriesModel, idx);
  38671. var itemGroup = new Group();
  38672. var symbolGroup = new Group();
  38673. itemGroup.add(polyline);
  38674. itemGroup.add(polygon);
  38675. itemGroup.add(symbolGroup);
  38676. updateSymbols(
  38677. polyline.shape.points, points, symbolGroup, data, idx, true
  38678. );
  38679. data.setItemGraphicEl(idx, itemGroup);
  38680. })
  38681. .update(function (newIdx, oldIdx) {
  38682. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  38683. var polyline = itemGroup.childAt(0);
  38684. var polygon = itemGroup.childAt(1);
  38685. var symbolGroup = itemGroup.childAt(2);
  38686. var target = {
  38687. shape: {
  38688. points: data.getItemLayout(newIdx)
  38689. }
  38690. };
  38691. if (!target.shape.points) {
  38692. return;
  38693. }
  38694. updateSymbols(
  38695. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  38696. );
  38697. updateProps(polyline, target, seriesModel);
  38698. updateProps(polygon, target, seriesModel);
  38699. data.setItemGraphicEl(newIdx, itemGroup);
  38700. })
  38701. .remove(function (idx) {
  38702. group.remove(oldData.getItemGraphicEl(idx));
  38703. })
  38704. .execute();
  38705. data.eachItemGraphicEl(function (itemGroup, idx) {
  38706. var itemModel = data.getItemModel(idx);
  38707. var polyline = itemGroup.childAt(0);
  38708. var polygon = itemGroup.childAt(1);
  38709. var symbolGroup = itemGroup.childAt(2);
  38710. var color = data.getItemVisual(idx, 'color');
  38711. group.add(itemGroup);
  38712. polyline.useStyle(
  38713. defaults(
  38714. itemModel.getModel('lineStyle').getLineStyle(),
  38715. {
  38716. fill: 'none',
  38717. stroke: color
  38718. }
  38719. )
  38720. );
  38721. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  38722. var areaStyleModel = itemModel.getModel('areaStyle');
  38723. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  38724. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  38725. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  38726. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  38727. polygon.ignore = polygonIgnore;
  38728. polygon.useStyle(
  38729. defaults(
  38730. areaStyleModel.getAreaStyle(),
  38731. {
  38732. fill: color,
  38733. opacity: 0.7
  38734. }
  38735. )
  38736. );
  38737. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  38738. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  38739. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  38740. var labelModel = itemModel.getModel('label');
  38741. var labelHoverModel = itemModel.getModel('emphasis.label');
  38742. symbolGroup.eachChild(function (symbolPath) {
  38743. symbolPath.setStyle(itemStyle);
  38744. symbolPath.hoverStyle = clone(itemHoverStyle);
  38745. setLabelStyle(
  38746. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  38747. {
  38748. labelFetcher: data.hostModel,
  38749. labelDataIndex: idx,
  38750. labelDimIndex: symbolPath.__dimIdx,
  38751. defaultText: data.get(data.dimensions[symbolPath.__dimIdx], idx),
  38752. autoColor: color,
  38753. isRectText: true
  38754. }
  38755. );
  38756. });
  38757. function onEmphasis() {
  38758. polygon.attr('ignore', hoverPolygonIgnore);
  38759. }
  38760. function onNormal() {
  38761. polygon.attr('ignore', polygonIgnore);
  38762. }
  38763. itemGroup.off('mouseover').off('mouseout').off('normal').off('emphasis');
  38764. itemGroup.on('emphasis', onEmphasis)
  38765. .on('mouseover', onEmphasis)
  38766. .on('normal', onNormal)
  38767. .on('mouseout', onNormal);
  38768. setHoverStyle(itemGroup);
  38769. });
  38770. this._data = data;
  38771. },
  38772. remove: function () {
  38773. this.group.removeAll();
  38774. this._data = null;
  38775. },
  38776. dispose: function () {}
  38777. });
  38778. /*
  38779. * Licensed to the Apache Software Foundation (ASF) under one
  38780. * or more contributor license agreements. See the NOTICE file
  38781. * distributed with this work for additional information
  38782. * regarding copyright ownership. The ASF licenses this file
  38783. * to you under the Apache License, Version 2.0 (the
  38784. * "License"); you may not use this file except in compliance
  38785. * with the License. You may obtain a copy of the License at
  38786. *
  38787. * http://www.apache.org/licenses/LICENSE-2.0
  38788. *
  38789. * Unless required by applicable law or agreed to in writing,
  38790. * software distributed under the License is distributed on an
  38791. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38792. * KIND, either express or implied. See the License for the
  38793. * specific language governing permissions and limitations
  38794. * under the License.
  38795. */
  38796. var radarLayout = function (ecModel) {
  38797. ecModel.eachSeriesByType('radar', function (seriesModel) {
  38798. var data = seriesModel.getData();
  38799. var points = [];
  38800. var coordSys = seriesModel.coordinateSystem;
  38801. if (!coordSys) {
  38802. return;
  38803. }
  38804. function pointsConverter(val, idx) {
  38805. points[idx] = points[idx] || [];
  38806. points[idx][i] = coordSys.dataToPoint(val, i);
  38807. }
  38808. var axes = coordSys.getIndicatorAxes();
  38809. for (var i = 0; i < axes.length; i++) {
  38810. data.each(data.mapDimension(axes[i].dim), pointsConverter);
  38811. }
  38812. data.each(function (idx) {
  38813. // Close polygon
  38814. points[idx][0] && points[idx].push(points[idx][0].slice());
  38815. data.setItemLayout(idx, points[idx]);
  38816. });
  38817. });
  38818. };
  38819. /*
  38820. * Licensed to the Apache Software Foundation (ASF) under one
  38821. * or more contributor license agreements. See the NOTICE file
  38822. * distributed with this work for additional information
  38823. * regarding copyright ownership. The ASF licenses this file
  38824. * to you under the Apache License, Version 2.0 (the
  38825. * "License"); you may not use this file except in compliance
  38826. * with the License. You may obtain a copy of the License at
  38827. *
  38828. * http://www.apache.org/licenses/LICENSE-2.0
  38829. *
  38830. * Unless required by applicable law or agreed to in writing,
  38831. * software distributed under the License is distributed on an
  38832. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38833. * KIND, either express or implied. See the License for the
  38834. * specific language governing permissions and limitations
  38835. * under the License.
  38836. */
  38837. // Backward compat for radar chart in 2
  38838. var backwardCompat$1 = function (option) {
  38839. var polarOptArr = option.polar;
  38840. if (polarOptArr) {
  38841. if (!isArray(polarOptArr)) {
  38842. polarOptArr = [polarOptArr];
  38843. }
  38844. var polarNotRadar = [];
  38845. each$1(polarOptArr, function (polarOpt, idx) {
  38846. if (polarOpt.indicator) {
  38847. if (polarOpt.type && !polarOpt.shape) {
  38848. polarOpt.shape = polarOpt.type;
  38849. }
  38850. option.radar = option.radar || [];
  38851. if (!isArray(option.radar)) {
  38852. option.radar = [option.radar];
  38853. }
  38854. option.radar.push(polarOpt);
  38855. }
  38856. else {
  38857. polarNotRadar.push(polarOpt);
  38858. }
  38859. });
  38860. option.polar = polarNotRadar;
  38861. }
  38862. each$1(option.series, function (seriesOpt) {
  38863. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  38864. seriesOpt.radarIndex = seriesOpt.polarIndex;
  38865. }
  38866. });
  38867. };
  38868. /*
  38869. * Licensed to the Apache Software Foundation (ASF) under one
  38870. * or more contributor license agreements. See the NOTICE file
  38871. * distributed with this work for additional information
  38872. * regarding copyright ownership. The ASF licenses this file
  38873. * to you under the Apache License, Version 2.0 (the
  38874. * "License"); you may not use this file except in compliance
  38875. * with the License. You may obtain a copy of the License at
  38876. *
  38877. * http://www.apache.org/licenses/LICENSE-2.0
  38878. *
  38879. * Unless required by applicable law or agreed to in writing,
  38880. * software distributed under the License is distributed on an
  38881. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38882. * KIND, either express or implied. See the License for the
  38883. * specific language governing permissions and limitations
  38884. * under the License.
  38885. */
  38886. // Must use radar component
  38887. registerVisual(dataColor('radar'));
  38888. registerVisual(visualSymbol('radar', 'circle'));
  38889. registerLayout(radarLayout);
  38890. registerProcessor(dataFilter('radar'));
  38891. registerPreprocessor(backwardCompat$1);
  38892. /*
  38893. * Licensed to the Apache Software Foundation (ASF) under one
  38894. * or more contributor license agreements. See the NOTICE file
  38895. * distributed with this work for additional information
  38896. * regarding copyright ownership. The ASF licenses this file
  38897. * to you under the Apache License, Version 2.0 (the
  38898. * "License"); you may not use this file except in compliance
  38899. * with the License. You may obtain a copy of the License at
  38900. *
  38901. * http://www.apache.org/licenses/LICENSE-2.0
  38902. *
  38903. * Unless required by applicable law or agreed to in writing,
  38904. * software distributed under the License is distributed on an
  38905. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38906. * KIND, either express or implied. See the License for the
  38907. * specific language governing permissions and limitations
  38908. * under the License.
  38909. */
  38910. // Fix for 南海诸岛
  38911. var geoCoord = [126, 25];
  38912. var points$1 = [
  38913. [[0, 3.5], [7, 11.2], [15, 11.9], [30, 7], [42, 0.7], [52, 0.7],
  38914. [56, 7.7], [59, 0.7], [64, 0.7], [64, 0], [5, 0], [0, 3.5]],
  38915. [[13, 16.1], [19, 14.7], [16, 21.7], [11, 23.1], [13, 16.1]],
  38916. [[12, 32.2], [14, 38.5], [15, 38.5], [13, 32.2], [12, 32.2]],
  38917. [[16, 47.6], [12, 53.2], [13, 53.2], [18, 47.6], [16, 47.6]],
  38918. [[6, 64.4], [8, 70], [9, 70], [8, 64.4], [6, 64.4]],
  38919. [[23, 82.6], [29, 79.8], [30, 79.8], [25, 82.6], [23, 82.6]],
  38920. [[37, 70.7], [43, 62.3], [44, 62.3], [39, 70.7], [37, 70.7]],
  38921. [[48, 51.1], [51, 45.5], [53, 45.5], [50, 51.1], [48, 51.1]],
  38922. [[51, 35], [51, 28.7], [53, 28.7], [53, 35], [51, 35]],
  38923. [[52, 22.4], [55, 17.5], [56, 17.5], [53, 22.4], [52, 22.4]],
  38924. [[58, 12.6], [62, 7], [63, 7], [60, 12.6], [58, 12.6]],
  38925. [[0, 3.5], [0, 93.1], [64, 93.1], [64, 0], [63, 0], [63, 92.4],
  38926. [1, 92.4], [1, 3.5], [0, 3.5]]
  38927. ];
  38928. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  38929. for (var k = 0; k < points$1[i$1].length; k++) {
  38930. points$1[i$1][k][0] /= 10.5;
  38931. points$1[i$1][k][1] /= -10.5 / 0.75;
  38932. points$1[i$1][k][0] += geoCoord[0];
  38933. points$1[i$1][k][1] += geoCoord[1];
  38934. }
  38935. }
  38936. var fixNanhai = function (mapType, regions) {
  38937. if (mapType === 'china') {
  38938. regions.push(new Region(
  38939. '南海诸岛',
  38940. map(points$1, function (exterior) {
  38941. return {
  38942. type: 'polygon',
  38943. exterior: exterior
  38944. };
  38945. }), geoCoord
  38946. ));
  38947. }
  38948. };
  38949. /*
  38950. * Licensed to the Apache Software Foundation (ASF) under one
  38951. * or more contributor license agreements. See the NOTICE file
  38952. * distributed with this work for additional information
  38953. * regarding copyright ownership. The ASF licenses this file
  38954. * to you under the Apache License, Version 2.0 (the
  38955. * "License"); you may not use this file except in compliance
  38956. * with the License. You may obtain a copy of the License at
  38957. *
  38958. * http://www.apache.org/licenses/LICENSE-2.0
  38959. *
  38960. * Unless required by applicable law or agreed to in writing,
  38961. * software distributed under the License is distributed on an
  38962. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38963. * KIND, either express or implied. See the License for the
  38964. * specific language governing permissions and limitations
  38965. * under the License.
  38966. */
  38967. var coordsOffsetMap = {
  38968. '南海诸岛': [32, 80],
  38969. // 全国
  38970. '广东': [0, -10],
  38971. '香港': [10, 5],
  38972. '澳门': [-10, 10],
  38973. //'北京': [-10, 0],
  38974. '天津': [5, 5]
  38975. };
  38976. var fixTextCoord = function (mapType, region) {
  38977. if (mapType === 'china') {
  38978. var coordFix = coordsOffsetMap[region.name];
  38979. if (coordFix) {
  38980. var cp = region.center;
  38981. cp[0] += coordFix[0] / 10.5;
  38982. cp[1] += -coordFix[1] / (10.5 / 0.75);
  38983. }
  38984. }
  38985. };
  38986. /*
  38987. * Licensed to the Apache Software Foundation (ASF) under one
  38988. * or more contributor license agreements. See the NOTICE file
  38989. * distributed with this work for additional information
  38990. * regarding copyright ownership. The ASF licenses this file
  38991. * to you under the Apache License, Version 2.0 (the
  38992. * "License"); you may not use this file except in compliance
  38993. * with the License. You may obtain a copy of the License at
  38994. *
  38995. * http://www.apache.org/licenses/LICENSE-2.0
  38996. *
  38997. * Unless required by applicable law or agreed to in writing,
  38998. * software distributed under the License is distributed on an
  38999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39000. * KIND, either express or implied. See the License for the
  39001. * specific language governing permissions and limitations
  39002. * under the License.
  39003. */
  39004. var geoCoordMap = {
  39005. 'Russia': [100, 60],
  39006. 'United States': [-99, 38],
  39007. 'United States of America': [-99, 38]
  39008. };
  39009. var fixGeoCoord = function (mapType, region) {
  39010. if (mapType === 'world') {
  39011. var geoCoord = geoCoordMap[region.name];
  39012. if (geoCoord) {
  39013. var cp = region.center;
  39014. cp[0] = geoCoord[0];
  39015. cp[1] = geoCoord[1];
  39016. }
  39017. }
  39018. };
  39019. /*
  39020. * Licensed to the Apache Software Foundation (ASF) under one
  39021. * or more contributor license agreements. See the NOTICE file
  39022. * distributed with this work for additional information
  39023. * regarding copyright ownership. The ASF licenses this file
  39024. * to you under the Apache License, Version 2.0 (the
  39025. * "License"); you may not use this file except in compliance
  39026. * with the License. You may obtain a copy of the License at
  39027. *
  39028. * http://www.apache.org/licenses/LICENSE-2.0
  39029. *
  39030. * Unless required by applicable law or agreed to in writing,
  39031. * software distributed under the License is distributed on an
  39032. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39033. * KIND, either express or implied. See the License for the
  39034. * specific language governing permissions and limitations
  39035. * under the License.
  39036. */
  39037. // Fix for 钓鱼岛
  39038. // var Region = require('../Region');
  39039. // var zrUtil = require('zrender/src/core/util');
  39040. // var geoCoord = [126, 25];
  39041. var points$2 = [
  39042. [
  39043. [123.45165252685547, 25.73527164402261],
  39044. [123.49731445312499, 25.73527164402261],
  39045. [123.49731445312499, 25.750734064600884],
  39046. [123.45165252685547, 25.750734064600884],
  39047. [123.45165252685547, 25.73527164402261]
  39048. ]
  39049. ];
  39050. var fixDiaoyuIsland = function (mapType, region) {
  39051. if (mapType === 'china' && region.name === '台湾') {
  39052. region.geometries.push({
  39053. type: 'polygon',
  39054. exterior: points$2[0]
  39055. });
  39056. }
  39057. };
  39058. /*
  39059. * Licensed to the Apache Software Foundation (ASF) under one
  39060. * or more contributor license agreements. See the NOTICE file
  39061. * distributed with this work for additional information
  39062. * regarding copyright ownership. The ASF licenses this file
  39063. * to you under the Apache License, Version 2.0 (the
  39064. * "License"); you may not use this file except in compliance
  39065. * with the License. You may obtain a copy of the License at
  39066. *
  39067. * http://www.apache.org/licenses/LICENSE-2.0
  39068. *
  39069. * Unless required by applicable law or agreed to in writing,
  39070. * software distributed under the License is distributed on an
  39071. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39072. * KIND, either express or implied. See the License for the
  39073. * specific language governing permissions and limitations
  39074. * under the License.
  39075. */
  39076. // Built-in GEO fixer.
  39077. var inner$7 = makeInner();
  39078. var geoJSONLoader = {
  39079. /**
  39080. * @param {string} mapName
  39081. * @param {Object} mapRecord {specialAreas, geoJSON}
  39082. * @return {Object} {regions, boundingRect}
  39083. */
  39084. load: function (mapName, mapRecord) {
  39085. var parsed = inner$7(mapRecord).parsed;
  39086. if (parsed) {
  39087. return parsed;
  39088. }
  39089. var specialAreas = mapRecord.specialAreas || {};
  39090. var geoJSON = mapRecord.geoJSON;
  39091. var regions;
  39092. // https://jsperf.com/try-catch-performance-overhead
  39093. try {
  39094. regions = geoJSON ? parseGeoJson$1(geoJSON) : [];
  39095. }
  39096. catch (e) {
  39097. throw new Error('Invalid geoJson format\n' + e.message);
  39098. }
  39099. each$1(regions, function (region) {
  39100. var regionName = region.name;
  39101. fixTextCoord(mapName, region);
  39102. fixGeoCoord(mapName, region);
  39103. fixDiaoyuIsland(mapName, region);
  39104. // Some area like Alaska in USA map needs to be tansformed
  39105. // to look better
  39106. var specialArea = specialAreas[regionName];
  39107. if (specialArea) {
  39108. region.transformTo(
  39109. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  39110. );
  39111. }
  39112. });
  39113. fixNanhai(mapName, regions);
  39114. return (inner$7(mapRecord).parsed = {
  39115. regions: regions,
  39116. boundingRect: getBoundingRect$1(regions)
  39117. });
  39118. }
  39119. };
  39120. function getBoundingRect$1(regions) {
  39121. var rect;
  39122. for (var i = 0; i < regions.length; i++) {
  39123. var regionRect = regions[i].getBoundingRect();
  39124. rect = rect || regionRect.clone();
  39125. rect.union(regionRect);
  39126. }
  39127. return rect;
  39128. }
  39129. /*
  39130. * Licensed to the Apache Software Foundation (ASF) under one
  39131. * or more contributor license agreements. See the NOTICE file
  39132. * distributed with this work for additional information
  39133. * regarding copyright ownership. The ASF licenses this file
  39134. * to you under the Apache License, Version 2.0 (the
  39135. * "License"); you may not use this file except in compliance
  39136. * with the License. You may obtain a copy of the License at
  39137. *
  39138. * http://www.apache.org/licenses/LICENSE-2.0
  39139. *
  39140. * Unless required by applicable law or agreed to in writing,
  39141. * software distributed under the License is distributed on an
  39142. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39143. * KIND, either express or implied. See the License for the
  39144. * specific language governing permissions and limitations
  39145. * under the License.
  39146. */
  39147. var inner$8 = makeInner();
  39148. var geoSVGLoader = {
  39149. /**
  39150. * @param {string} mapName
  39151. * @param {Object} mapRecord {specialAreas, geoJSON}
  39152. * @return {Object} {root, boundingRect}
  39153. */
  39154. load: function (mapName, mapRecord) {
  39155. var originRoot = inner$8(mapRecord).originRoot;
  39156. if (originRoot) {
  39157. return {
  39158. root: originRoot,
  39159. boundingRect: inner$8(mapRecord).boundingRect
  39160. };
  39161. }
  39162. var graphic = buildGraphic(mapRecord);
  39163. inner$8(mapRecord).originRoot = graphic.root;
  39164. inner$8(mapRecord).boundingRect = graphic.boundingRect;
  39165. return graphic;
  39166. },
  39167. makeGraphic: function (mapName, mapRecord, hostKey) {
  39168. // For performance consideration (in large SVG), graphic only maked
  39169. // when necessary and reuse them according to hostKey.
  39170. var field = inner$8(mapRecord);
  39171. var rootMap = field.rootMap || (field.rootMap = createHashMap());
  39172. var root = rootMap.get(hostKey);
  39173. if (root) {
  39174. return root;
  39175. }
  39176. var originRoot = field.originRoot;
  39177. var boundingRect = field.boundingRect;
  39178. // For performance, if originRoot is not used by a view,
  39179. // assign it to a view, but not reproduce graphic elements.
  39180. if (!field.originRootHostKey) {
  39181. field.originRootHostKey = hostKey;
  39182. root = originRoot;
  39183. }
  39184. else {
  39185. root = buildGraphic(mapRecord, boundingRect).root;
  39186. }
  39187. return rootMap.set(hostKey, root);
  39188. },
  39189. removeGraphic: function (mapName, mapRecord, hostKey) {
  39190. var field = inner$8(mapRecord);
  39191. var rootMap = field.rootMap;
  39192. rootMap && rootMap.removeKey(hostKey);
  39193. if (hostKey === field.originRootHostKey) {
  39194. field.originRootHostKey = null;
  39195. }
  39196. }
  39197. };
  39198. function buildGraphic(mapRecord, boundingRect) {
  39199. var svgXML = mapRecord.svgXML;
  39200. var result;
  39201. var root;
  39202. try {
  39203. result = svgXML && parseSVG(svgXML, {
  39204. ignoreViewBox: true,
  39205. ignoreRootClip: true
  39206. }) || {};
  39207. root = result.root;
  39208. assert$1(root != null);
  39209. }
  39210. catch (e) {
  39211. throw new Error('Invalid svg format\n' + e.message);
  39212. }
  39213. var svgWidth = result.width;
  39214. var svgHeight = result.height;
  39215. var viewBoxRect = result.viewBoxRect;
  39216. if (!boundingRect) {
  39217. boundingRect = (svgWidth == null || svgHeight == null)
  39218. // If svg width / height not specified, calculate
  39219. // bounding rect as the width / height
  39220. ? root.getBoundingRect()
  39221. : new BoundingRect(0, 0, 0, 0);
  39222. if (svgWidth != null) {
  39223. boundingRect.width = svgWidth;
  39224. }
  39225. if (svgHeight != null) {
  39226. boundingRect.height = svgHeight;
  39227. }
  39228. }
  39229. if (viewBoxRect) {
  39230. var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect.width, boundingRect.height);
  39231. var elRoot = root;
  39232. root = new Group();
  39233. root.add(elRoot);
  39234. elRoot.scale = viewBoxTransform.scale;
  39235. elRoot.position = viewBoxTransform.position;
  39236. }
  39237. root.setClipPath(new Rect({
  39238. shape: boundingRect.plain()
  39239. }));
  39240. return {
  39241. root: root,
  39242. boundingRect: boundingRect
  39243. };
  39244. }
  39245. /*
  39246. * Licensed to the Apache Software Foundation (ASF) under one
  39247. * or more contributor license agreements. See the NOTICE file
  39248. * distributed with this work for additional information
  39249. * regarding copyright ownership. The ASF licenses this file
  39250. * to you under the Apache License, Version 2.0 (the
  39251. * "License"); you may not use this file except in compliance
  39252. * with the License. You may obtain a copy of the License at
  39253. *
  39254. * http://www.apache.org/licenses/LICENSE-2.0
  39255. *
  39256. * Unless required by applicable law or agreed to in writing,
  39257. * software distributed under the License is distributed on an
  39258. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39259. * KIND, either express or implied. See the License for the
  39260. * specific language governing permissions and limitations
  39261. * under the License.
  39262. */
  39263. var loaders = {
  39264. geoJSON: geoJSONLoader,
  39265. svg: geoSVGLoader
  39266. };
  39267. var geoSourceManager = {
  39268. /**
  39269. * @param {string} mapName
  39270. * @param {Object} nameMap
  39271. * @return {Object} source {regions, regionsMap, nameCoordMap, boundingRect}
  39272. */
  39273. load: function (mapName, nameMap) {
  39274. var regions = [];
  39275. var regionsMap = createHashMap();
  39276. var nameCoordMap = createHashMap();
  39277. var boundingRect;
  39278. var mapRecords = retrieveMap(mapName);
  39279. each$1(mapRecords, function (record) {
  39280. var singleSource = loaders[record.type].load(mapName, record);
  39281. each$1(singleSource.regions, function (region) {
  39282. var regionName = region.name;
  39283. // Try use the alias in geoNameMap
  39284. if (nameMap && nameMap.hasOwnProperty(regionName)) {
  39285. region = region.cloneShallow(regionName = nameMap[regionName]);
  39286. }
  39287. regions.push(region);
  39288. regionsMap.set(regionName, region);
  39289. nameCoordMap.set(regionName, region.center);
  39290. });
  39291. var rect = singleSource.boundingRect;
  39292. if (rect) {
  39293. boundingRect
  39294. ? boundingRect.union(rect)
  39295. : (boundingRect = rect.clone());
  39296. }
  39297. });
  39298. return {
  39299. regions: regions,
  39300. regionsMap: regionsMap,
  39301. nameCoordMap: nameCoordMap,
  39302. // FIXME Always return new ?
  39303. boundingRect: boundingRect || new BoundingRect(0, 0, 0, 0)
  39304. };
  39305. },
  39306. /**
  39307. * @param {string} mapName
  39308. * @param {string} hostKey For cache.
  39309. * @return {Array.<module:zrender/Element>} Roots.
  39310. */
  39311. makeGraphic: makeInvoker('makeGraphic'),
  39312. /**
  39313. * @param {string} mapName
  39314. * @param {string} hostKey For cache.
  39315. */
  39316. removeGraphic: makeInvoker('removeGraphic')
  39317. };
  39318. function makeInvoker(methodName) {
  39319. return function (mapName, hostKey) {
  39320. var mapRecords = retrieveMap(mapName);
  39321. var results = [];
  39322. each$1(mapRecords, function (record) {
  39323. var method = loaders[record.type][methodName];
  39324. method && results.push(method(mapName, record, hostKey));
  39325. });
  39326. return results;
  39327. };
  39328. }
  39329. function mapNotExistsError(mapName) {
  39330. if (__DEV__) {
  39331. console.error(
  39332. 'Map ' + mapName + ' not exists. You can download map file on http://echarts.baidu.com/download-map.html'
  39333. );
  39334. }
  39335. }
  39336. function retrieveMap(mapName) {
  39337. var mapRecords = mapDataStorage.retrieveMap(mapName) || [];
  39338. if (__DEV__) {
  39339. if (!mapRecords.length) {
  39340. mapNotExistsError(mapName);
  39341. }
  39342. }
  39343. return mapRecords;
  39344. }
  39345. /*
  39346. * Licensed to the Apache Software Foundation (ASF) under one
  39347. * or more contributor license agreements. See the NOTICE file
  39348. * distributed with this work for additional information
  39349. * regarding copyright ownership. The ASF licenses this file
  39350. * to you under the Apache License, Version 2.0 (the
  39351. * "License"); you may not use this file except in compliance
  39352. * with the License. You may obtain a copy of the License at
  39353. *
  39354. * http://www.apache.org/licenses/LICENSE-2.0
  39355. *
  39356. * Unless required by applicable law or agreed to in writing,
  39357. * software distributed under the License is distributed on an
  39358. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39359. * KIND, either express or implied. See the License for the
  39360. * specific language governing permissions and limitations
  39361. * under the License.
  39362. */
  39363. var MapSeries = SeriesModel.extend({
  39364. type: 'series.map',
  39365. dependencies: ['geo'],
  39366. layoutMode: 'box',
  39367. /**
  39368. * Only first map series of same mapType will drawMap
  39369. * @type {boolean}
  39370. */
  39371. needsDrawMap: false,
  39372. /**
  39373. * Group of all map series with same mapType
  39374. * @type {boolean}
  39375. */
  39376. seriesGroup: [],
  39377. getInitialData: function (option) {
  39378. var data = createListSimply(this, ['value']);
  39379. var valueDim = data.mapDimension('value');
  39380. var dataNameMap = createHashMap();
  39381. var selectTargetList = [];
  39382. var toAppendNames = [];
  39383. for (var i = 0, len = data.count(); i < len; i++) {
  39384. var name = data.getName(i);
  39385. dataNameMap.set(name, true);
  39386. selectTargetList.push({
  39387. name: name,
  39388. value: data.get(valueDim, i),
  39389. selected: retrieveRawAttr(data, i, 'selected')
  39390. });
  39391. }
  39392. var geoSource = geoSourceManager.load(this.getMapType(), this.option.nameMap);
  39393. each$1(geoSource.regions, function (region) {
  39394. var name = region.name;
  39395. if (!dataNameMap.get(name)) {
  39396. selectTargetList.push({name: name});
  39397. toAppendNames.push(name);
  39398. }
  39399. });
  39400. this.updateSelectedMap(selectTargetList);
  39401. // Complete data with missing regions. The consequent processes (like visual
  39402. // map and render) can not be performed without a "full data". For example,
  39403. // find `dataIndex` by name.
  39404. data.appendValues([], toAppendNames);
  39405. return data;
  39406. },
  39407. /**
  39408. * If no host geo model, return null, which means using a
  39409. * inner exclusive geo model.
  39410. */
  39411. getHostGeoModel: function () {
  39412. var geoIndex = this.option.geoIndex;
  39413. return geoIndex != null
  39414. ? this.dependentModels.geo[geoIndex]
  39415. : null;
  39416. },
  39417. getMapType: function () {
  39418. return (this.getHostGeoModel() || this).option.map;
  39419. },
  39420. // _fillOption: function (option, mapName) {
  39421. // Shallow clone
  39422. // option = zrUtil.extend({}, option);
  39423. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  39424. // return option;
  39425. // },
  39426. getRawValue: function (dataIndex) {
  39427. // Use value stored in data instead because it is calculated from multiple series
  39428. // FIXME Provide all value of multiple series ?
  39429. var data = this.getData();
  39430. return data.get(data.mapDimension('value'), dataIndex);
  39431. },
  39432. /**
  39433. * Get model of region
  39434. * @param {string} name
  39435. * @return {module:echarts/model/Model}
  39436. */
  39437. getRegionModel: function (regionName) {
  39438. var data = this.getData();
  39439. return data.getItemModel(data.indexOfName(regionName));
  39440. },
  39441. /**
  39442. * Map tooltip formatter
  39443. *
  39444. * @param {number} dataIndex
  39445. */
  39446. formatTooltip: function (dataIndex) {
  39447. // FIXME orignalData and data is a bit confusing
  39448. var data = this.getData();
  39449. var formattedValue = addCommas(this.getRawValue(dataIndex));
  39450. var name = data.getName(dataIndex);
  39451. var seriesGroup = this.seriesGroup;
  39452. var seriesNames = [];
  39453. for (var i = 0; i < seriesGroup.length; i++) {
  39454. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  39455. var valueDim = data.mapDimension('value');
  39456. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  39457. seriesNames.push(
  39458. encodeHTML(seriesGroup[i].name)
  39459. );
  39460. }
  39461. }
  39462. return seriesNames.join(', ') + '<br />'
  39463. + encodeHTML(name + ' : ' + formattedValue);
  39464. },
  39465. /**
  39466. * @implement
  39467. */
  39468. getTooltipPosition: function (dataIndex) {
  39469. if (dataIndex != null) {
  39470. var name = this.getData().getName(dataIndex);
  39471. var geo = this.coordinateSystem;
  39472. var region = geo.getRegion(name);
  39473. return region && geo.dataToPoint(region.center);
  39474. }
  39475. },
  39476. setZoom: function (zoom) {
  39477. this.option.zoom = zoom;
  39478. },
  39479. setCenter: function (center) {
  39480. this.option.center = center;
  39481. },
  39482. defaultOption: {
  39483. // 一级层叠
  39484. zlevel: 0,
  39485. // 二级层叠
  39486. z: 2,
  39487. coordinateSystem: 'geo',
  39488. // map should be explicitly specified since ec3.
  39489. map: '',
  39490. // If `geoIndex` is not specified, a exclusive geo will be
  39491. // created. Otherwise use the specified geo component, and
  39492. // `map` and `mapType` are ignored.
  39493. // geoIndex: 0,
  39494. // 'center' | 'left' | 'right' | 'x%' | {number}
  39495. left: 'center',
  39496. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  39497. top: 'center',
  39498. // right
  39499. // bottom
  39500. // width:
  39501. // height
  39502. // Aspect is width / height. Inited to be geoJson bbox aspect
  39503. // This parameter is used for scale this aspect
  39504. aspectScale: 0.75,
  39505. ///// Layout with center and size
  39506. // If you wan't to put map in a fixed size box with right aspect ratio
  39507. // This two properties may more conveninet
  39508. // layoutCenter: [50%, 50%]
  39509. // layoutSize: 100
  39510. // 数值合并方式,默认加和,可选为:
  39511. // 'sum' | 'average' | 'max' | 'min'
  39512. // mapValueCalculation: 'sum',
  39513. // 地图数值计算结果小数精度
  39514. // mapValuePrecision: 0,
  39515. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  39516. showLegendSymbol: true,
  39517. // 选择模式,默认关闭,可选single,multiple
  39518. // selectedMode: false,
  39519. dataRangeHoverLink: true,
  39520. // 是否开启缩放及漫游模式
  39521. // roam: false,
  39522. // Define left-top, right-bottom coords to control view
  39523. // For example, [ [180, 90], [-180, -90] ],
  39524. // higher priority than center and zoom
  39525. boundingCoords: null,
  39526. // Default on center of map
  39527. center: null,
  39528. zoom: 1,
  39529. scaleLimit: null,
  39530. label: {
  39531. show: false,
  39532. color: '#000'
  39533. },
  39534. // scaleLimit: null,
  39535. itemStyle: {
  39536. borderWidth: 0.5,
  39537. borderColor: '#444',
  39538. areaColor: '#eee'
  39539. },
  39540. emphasis: {
  39541. label: {
  39542. show: true,
  39543. color: 'rgb(100,0,0)'
  39544. },
  39545. itemStyle: {
  39546. areaColor: 'rgba(255,215,0,0.8)'
  39547. }
  39548. }
  39549. }
  39550. });
  39551. mixin(MapSeries, selectableMixin);
  39552. /*
  39553. * Licensed to the Apache Software Foundation (ASF) under one
  39554. * or more contributor license agreements. See the NOTICE file
  39555. * distributed with this work for additional information
  39556. * regarding copyright ownership. The ASF licenses this file
  39557. * to you under the Apache License, Version 2.0 (the
  39558. * "License"); you may not use this file except in compliance
  39559. * with the License. You may obtain a copy of the License at
  39560. *
  39561. * http://www.apache.org/licenses/LICENSE-2.0
  39562. *
  39563. * Unless required by applicable law or agreed to in writing,
  39564. * software distributed under the License is distributed on an
  39565. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39566. * KIND, either express or implied. See the License for the
  39567. * specific language governing permissions and limitations
  39568. * under the License.
  39569. */
  39570. var ATTR = '\0_ec_interaction_mutex';
  39571. function take(zr, resourceKey, userKey) {
  39572. var store = getStore(zr);
  39573. store[resourceKey] = userKey;
  39574. }
  39575. function release(zr, resourceKey, userKey) {
  39576. var store = getStore(zr);
  39577. var uKey = store[resourceKey];
  39578. if (uKey === userKey) {
  39579. store[resourceKey] = null;
  39580. }
  39581. }
  39582. function isTaken(zr, resourceKey) {
  39583. return !!getStore(zr)[resourceKey];
  39584. }
  39585. function getStore(zr) {
  39586. return zr[ATTR] || (zr[ATTR] = {});
  39587. }
  39588. /**
  39589. * payload: {
  39590. * type: 'takeGlobalCursor',
  39591. * key: 'dataZoomSelect', or 'brush', or ...,
  39592. * If no userKey, release global cursor.
  39593. * }
  39594. */
  39595. registerAction(
  39596. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  39597. function () {}
  39598. );
  39599. /*
  39600. * Licensed to the Apache Software Foundation (ASF) under one
  39601. * or more contributor license agreements. See the NOTICE file
  39602. * distributed with this work for additional information
  39603. * regarding copyright ownership. The ASF licenses this file
  39604. * to you under the Apache License, Version 2.0 (the
  39605. * "License"); you may not use this file except in compliance
  39606. * with the License. You may obtain a copy of the License at
  39607. *
  39608. * http://www.apache.org/licenses/LICENSE-2.0
  39609. *
  39610. * Unless required by applicable law or agreed to in writing,
  39611. * software distributed under the License is distributed on an
  39612. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39613. * KIND, either express or implied. See the License for the
  39614. * specific language governing permissions and limitations
  39615. * under the License.
  39616. */
  39617. /**
  39618. * @alias module:echarts/component/helper/RoamController
  39619. * @constructor
  39620. * @mixin {module:zrender/mixin/Eventful}
  39621. *
  39622. * @param {module:zrender/zrender~ZRender} zr
  39623. */
  39624. function RoamController(zr) {
  39625. /**
  39626. * @type {Function}
  39627. */
  39628. this.pointerChecker;
  39629. /**
  39630. * @type {module:zrender}
  39631. */
  39632. this._zr = zr;
  39633. /**
  39634. * @type {Object}
  39635. */
  39636. this._opt = {};
  39637. // Avoid two roamController bind the same handler
  39638. var bind$$1 = bind;
  39639. var mousedownHandler = bind$$1(mousedown, this);
  39640. var mousemoveHandler = bind$$1(mousemove, this);
  39641. var mouseupHandler = bind$$1(mouseup, this);
  39642. var mousewheelHandler = bind$$1(mousewheel, this);
  39643. var pinchHandler = bind$$1(pinch, this);
  39644. Eventful.call(this);
  39645. /**
  39646. * @param {Function} pointerChecker
  39647. * input: x, y
  39648. * output: boolean
  39649. */
  39650. this.setPointerChecker = function (pointerChecker) {
  39651. this.pointerChecker = pointerChecker;
  39652. };
  39653. /**
  39654. * Notice: only enable needed types. For example, if 'zoom'
  39655. * is not needed, 'zoom' should not be enabled, otherwise
  39656. * default mousewheel behaviour (scroll page) will be disabled.
  39657. *
  39658. * @param {boolean|string} [controlType=true] Specify the control type,
  39659. * which can be null/undefined or true/false
  39660. * or 'pan/move' or 'zoom'/'scale'
  39661. * @param {Object} [opt]
  39662. * @param {Object} [opt.zoomOnMouseWheel=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39663. * @param {Object} [opt.moveOnMouseMove=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39664. * @param {Object} [opt.moveOnMouseWheel=false] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39665. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  39666. */
  39667. this.enable = function (controlType, opt) {
  39668. // Disable previous first
  39669. this.disable();
  39670. this._opt = defaults(clone(opt) || {}, {
  39671. zoomOnMouseWheel: true,
  39672. moveOnMouseMove: true,
  39673. // By default, wheel do not trigger move.
  39674. moveOnMouseWheel: false,
  39675. preventDefaultMouseMove: true
  39676. });
  39677. if (controlType == null) {
  39678. controlType = true;
  39679. }
  39680. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  39681. zr.on('mousedown', mousedownHandler);
  39682. zr.on('mousemove', mousemoveHandler);
  39683. zr.on('mouseup', mouseupHandler);
  39684. }
  39685. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  39686. zr.on('mousewheel', mousewheelHandler);
  39687. zr.on('pinch', pinchHandler);
  39688. }
  39689. };
  39690. this.disable = function () {
  39691. zr.off('mousedown', mousedownHandler);
  39692. zr.off('mousemove', mousemoveHandler);
  39693. zr.off('mouseup', mouseupHandler);
  39694. zr.off('mousewheel', mousewheelHandler);
  39695. zr.off('pinch', pinchHandler);
  39696. };
  39697. this.dispose = this.disable;
  39698. this.isDragging = function () {
  39699. return this._dragging;
  39700. };
  39701. this.isPinching = function () {
  39702. return this._pinching;
  39703. };
  39704. }
  39705. mixin(RoamController, Eventful);
  39706. function mousedown(e) {
  39707. if (isMiddleOrRightButtonOnMouseUpDown(e)
  39708. || (e.target && e.target.draggable)
  39709. ) {
  39710. return;
  39711. }
  39712. var x = e.offsetX;
  39713. var y = e.offsetY;
  39714. // Only check on mosedown, but not mousemove.
  39715. // Mouse can be out of target when mouse moving.
  39716. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  39717. this._x = x;
  39718. this._y = y;
  39719. this._dragging = true;
  39720. }
  39721. }
  39722. function mousemove(e) {
  39723. if (!this._dragging
  39724. || !isAvailableBehavior('moveOnMouseMove', e, this._opt)
  39725. || e.gestureEvent === 'pinch'
  39726. || isTaken(this._zr, 'globalPan')
  39727. ) {
  39728. return;
  39729. }
  39730. var x = e.offsetX;
  39731. var y = e.offsetY;
  39732. var oldX = this._x;
  39733. var oldY = this._y;
  39734. var dx = x - oldX;
  39735. var dy = y - oldY;
  39736. this._x = x;
  39737. this._y = y;
  39738. this._opt.preventDefaultMouseMove && stop(e.event);
  39739. trigger(this, 'pan', 'moveOnMouseMove', e, {
  39740. dx: dx, dy: dy, oldX: oldX, oldY: oldY, newX: x, newY: y
  39741. });
  39742. }
  39743. function mouseup(e) {
  39744. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  39745. this._dragging = false;
  39746. }
  39747. }
  39748. function mousewheel(e) {
  39749. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  39750. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  39751. var wheelDelta = e.wheelDelta;
  39752. var absWheelDeltaDelta = Math.abs(wheelDelta);
  39753. var originX = e.offsetX;
  39754. var originY = e.offsetY;
  39755. // wheelDelta maybe -0 in chrome mac.
  39756. if (wheelDelta === 0 || (!shouldZoom && !shouldMove)) {
  39757. return;
  39758. }
  39759. // If both `shouldZoom` and `shouldMove` is true, trigger
  39760. // their event both, and the final behavior is determined
  39761. // by event listener themselves.
  39762. if (shouldZoom) {
  39763. // Convenience:
  39764. // Mac and VM Windows on Mac: scroll up: zoom out.
  39765. // Windows: scroll up: zoom in.
  39766. // FIXME: Should do more test in different environment.
  39767. // wheelDelta is too complicated in difference nvironment
  39768. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  39769. // although it has been normallized by zrender.
  39770. // wheelDelta of mouse wheel is bigger than touch pad.
  39771. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  39772. var scale = wheelDelta > 0 ? factor : 1 / factor;
  39773. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  39774. scale: scale, originX: originX, originY: originY
  39775. });
  39776. }
  39777. if (shouldMove) {
  39778. // FIXME: Should do more test in different environment.
  39779. var absDelta = Math.abs(wheelDelta);
  39780. // wheelDelta of mouse wheel is bigger than touch pad.
  39781. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  39782. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  39783. scrollDelta: scrollDelta, originX: originX, originY: originY
  39784. });
  39785. }
  39786. }
  39787. function pinch(e) {
  39788. if (isTaken(this._zr, 'globalPan')) {
  39789. return;
  39790. }
  39791. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  39792. checkPointerAndTrigger(this, 'zoom', null, e, {
  39793. scale: scale, originX: e.pinchX, originY: e.pinchY
  39794. });
  39795. }
  39796. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  39797. if (controller.pointerChecker
  39798. && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)
  39799. ) {
  39800. // When mouse is out of roamController rect,
  39801. // default befavoius should not be be disabled, otherwise
  39802. // page sliding is disabled, contrary to expectation.
  39803. stop(e.event);
  39804. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  39805. }
  39806. }
  39807. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  39808. // Also provide behavior checker for event listener, for some case that
  39809. // multiple components share one listener.
  39810. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  39811. controller.trigger(eventName, contollerEvent);
  39812. }
  39813. // settings: {
  39814. // zoomOnMouseWheel
  39815. // moveOnMouseMove
  39816. // moveOnMouseWheel
  39817. // }
  39818. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  39819. function isAvailableBehavior(behaviorToCheck, e, settings) {
  39820. var setting = settings[behaviorToCheck];
  39821. return !behaviorToCheck || (
  39822. setting && (!isString(setting) || e.event[setting + 'Key'])
  39823. );
  39824. }
  39825. /*
  39826. * Licensed to the Apache Software Foundation (ASF) under one
  39827. * or more contributor license agreements. See the NOTICE file
  39828. * distributed with this work for additional information
  39829. * regarding copyright ownership. The ASF licenses this file
  39830. * to you under the Apache License, Version 2.0 (the
  39831. * "License"); you may not use this file except in compliance
  39832. * with the License. You may obtain a copy of the License at
  39833. *
  39834. * http://www.apache.org/licenses/LICENSE-2.0
  39835. *
  39836. * Unless required by applicable law or agreed to in writing,
  39837. * software distributed under the License is distributed on an
  39838. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39839. * KIND, either express or implied. See the License for the
  39840. * specific language governing permissions and limitations
  39841. * under the License.
  39842. */
  39843. /**
  39844. * For geo and graph.
  39845. *
  39846. * @param {Object} controllerHost
  39847. * @param {module:zrender/Element} controllerHost.target
  39848. */
  39849. function updateViewOnPan(controllerHost, dx, dy) {
  39850. var target = controllerHost.target;
  39851. var pos = target.position;
  39852. pos[0] += dx;
  39853. pos[1] += dy;
  39854. target.dirty();
  39855. }
  39856. /**
  39857. * For geo and graph.
  39858. *
  39859. * @param {Object} controllerHost
  39860. * @param {module:zrender/Element} controllerHost.target
  39861. * @param {number} controllerHost.zoom
  39862. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  39863. */
  39864. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  39865. var target = controllerHost.target;
  39866. var zoomLimit = controllerHost.zoomLimit;
  39867. var pos = target.position;
  39868. var scale = target.scale;
  39869. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  39870. newZoom *= zoomDelta;
  39871. if (zoomLimit) {
  39872. var zoomMin = zoomLimit.min || 0;
  39873. var zoomMax = zoomLimit.max || Infinity;
  39874. newZoom = Math.max(
  39875. Math.min(zoomMax, newZoom),
  39876. zoomMin
  39877. );
  39878. }
  39879. var zoomScale = newZoom / controllerHost.zoom;
  39880. controllerHost.zoom = newZoom;
  39881. // Keep the mouse center when scaling
  39882. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  39883. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  39884. scale[0] *= zoomScale;
  39885. scale[1] *= zoomScale;
  39886. target.dirty();
  39887. }
  39888. /*
  39889. * Licensed to the Apache Software Foundation (ASF) under one
  39890. * or more contributor license agreements. See the NOTICE file
  39891. * distributed with this work for additional information
  39892. * regarding copyright ownership. The ASF licenses this file
  39893. * to you under the Apache License, Version 2.0 (the
  39894. * "License"); you may not use this file except in compliance
  39895. * with the License. You may obtain a copy of the License at
  39896. *
  39897. * http://www.apache.org/licenses/LICENSE-2.0
  39898. *
  39899. * Unless required by applicable law or agreed to in writing,
  39900. * software distributed under the License is distributed on an
  39901. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39902. * KIND, either express or implied. See the License for the
  39903. * specific language governing permissions and limitations
  39904. * under the License.
  39905. */
  39906. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  39907. /**
  39908. * Avoid that: mouse click on a elements that is over geo or graph,
  39909. * but roam is triggered.
  39910. */
  39911. function onIrrelevantElement(e, api, targetCoordSysModel) {
  39912. var model = api.getComponentByElement(e.topTarget);
  39913. // If model is axisModel, it works only if it is injected with coordinateSystem.
  39914. var coordSys = model && model.coordinateSystem;
  39915. return model
  39916. && model !== targetCoordSysModel
  39917. && !IRRELEVANT_EXCLUDES[model.mainType]
  39918. && (coordSys && coordSys.model !== targetCoordSysModel);
  39919. }
  39920. /*
  39921. * Licensed to the Apache Software Foundation (ASF) under one
  39922. * or more contributor license agreements. See the NOTICE file
  39923. * distributed with this work for additional information
  39924. * regarding copyright ownership. The ASF licenses this file
  39925. * to you under the Apache License, Version 2.0 (the
  39926. * "License"); you may not use this file except in compliance
  39927. * with the License. You may obtain a copy of the License at
  39928. *
  39929. * http://www.apache.org/licenses/LICENSE-2.0
  39930. *
  39931. * Unless required by applicable law or agreed to in writing,
  39932. * software distributed under the License is distributed on an
  39933. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39934. * KIND, either express or implied. See the License for the
  39935. * specific language governing permissions and limitations
  39936. * under the License.
  39937. */
  39938. function getFixedItemStyle(model, scale) {
  39939. var itemStyle = model.getItemStyle();
  39940. var areaColor = model.get('areaColor');
  39941. // If user want the color not to be changed when hover,
  39942. // they should both set areaColor and color to be null.
  39943. if (areaColor != null) {
  39944. itemStyle.fill = areaColor;
  39945. }
  39946. return itemStyle;
  39947. }
  39948. function updateMapSelectHandler(mapDraw, mapOrGeoModel, regionsGroup, api, fromView) {
  39949. regionsGroup.off('click');
  39950. regionsGroup.off('mousedown');
  39951. if (mapOrGeoModel.get('selectedMode')) {
  39952. regionsGroup.on('mousedown', function () {
  39953. mapDraw._mouseDownFlag = true;
  39954. });
  39955. regionsGroup.on('click', function (e) {
  39956. if (!mapDraw._mouseDownFlag) {
  39957. return;
  39958. }
  39959. mapDraw._mouseDownFlag = false;
  39960. var el = e.target;
  39961. while (!el.__regions) {
  39962. el = el.parent;
  39963. }
  39964. if (!el) {
  39965. return;
  39966. }
  39967. var action = {
  39968. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  39969. batch: map(el.__regions, function (region) {
  39970. return {
  39971. name: region.name,
  39972. from: fromView.uid
  39973. };
  39974. })
  39975. };
  39976. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  39977. api.dispatchAction(action);
  39978. updateMapSelected(mapOrGeoModel, regionsGroup);
  39979. });
  39980. }
  39981. }
  39982. function updateMapSelected(mapOrGeoModel, regionsGroup) {
  39983. // FIXME
  39984. regionsGroup.eachChild(function (otherRegionEl) {
  39985. each$1(otherRegionEl.__regions, function (region) {
  39986. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  39987. });
  39988. });
  39989. }
  39990. /**
  39991. * @alias module:echarts/component/helper/MapDraw
  39992. * @param {module:echarts/ExtensionAPI} api
  39993. * @param {boolean} updateGroup
  39994. */
  39995. function MapDraw(api, updateGroup) {
  39996. var group = new Group();
  39997. /**
  39998. * @type {string}
  39999. * @private
  40000. */
  40001. this.uid = getUID('ec_map_draw');
  40002. /**
  40003. * @type {module:echarts/component/helper/RoamController}
  40004. * @private
  40005. */
  40006. this._controller = new RoamController(api.getZr());
  40007. /**
  40008. * @type {Object} {target, zoom, zoomLimit}
  40009. * @private
  40010. */
  40011. this._controllerHost = {target: updateGroup ? group : null};
  40012. /**
  40013. * @type {module:zrender/container/Group}
  40014. * @readOnly
  40015. */
  40016. this.group = group;
  40017. /**
  40018. * @type {boolean}
  40019. * @private
  40020. */
  40021. this._updateGroup = updateGroup;
  40022. /**
  40023. * This flag is used to make sure that only one among
  40024. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  40025. * action may be triggered when `pan`, which is unexpected.
  40026. * @type {booelan}
  40027. */
  40028. this._mouseDownFlag;
  40029. /**
  40030. * @type {string}
  40031. */
  40032. this._mapName;
  40033. /**
  40034. * @type {boolean}
  40035. */
  40036. this._initialized;
  40037. /**
  40038. * @type {module:zrender/container/Group}
  40039. */
  40040. group.add(this._regionsGroup = new Group());
  40041. /**
  40042. * @type {module:zrender/container/Group}
  40043. */
  40044. group.add(this._backgroundGroup = new Group());
  40045. }
  40046. MapDraw.prototype = {
  40047. constructor: MapDraw,
  40048. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  40049. var isGeo = mapOrGeoModel.mainType === 'geo';
  40050. // Map series has data. GEO model that controlled by map series
  40051. // will be assigned with map data. Other GEO model has no data.
  40052. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  40053. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  40054. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  40055. data = mapSeries.getData();
  40056. }
  40057. });
  40058. var geo = mapOrGeoModel.coordinateSystem;
  40059. this._updateBackground(geo);
  40060. var regionsGroup = this._regionsGroup;
  40061. var group = this.group;
  40062. var scale = geo.scale;
  40063. var transform = {
  40064. position: geo.position,
  40065. scale: scale
  40066. };
  40067. // No animation when first draw or in action
  40068. if (!regionsGroup.childAt(0) || payload) {
  40069. group.attr(transform);
  40070. }
  40071. else {
  40072. updateProps(group, transform, mapOrGeoModel);
  40073. }
  40074. regionsGroup.removeAll();
  40075. var itemStyleAccessPath = ['itemStyle'];
  40076. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  40077. var labelAccessPath = ['label'];
  40078. var hoverLabelAccessPath = ['emphasis', 'label'];
  40079. var nameMap = createHashMap();
  40080. each$1(geo.regions, function (region) {
  40081. // Consider in GeoJson properties.name may be duplicated, for example,
  40082. // there is multiple region named "United Kindom" or "France" (so many
  40083. // colonies). And it is not appropriate to merge them in geo, which
  40084. // will make them share the same label and bring trouble in label
  40085. // location calculation.
  40086. var regionGroup = nameMap.get(region.name)
  40087. || nameMap.set(region.name, new Group());
  40088. var compoundPath = new CompoundPath({
  40089. shape: {
  40090. paths: []
  40091. }
  40092. });
  40093. regionGroup.add(compoundPath);
  40094. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  40095. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  40096. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  40097. var itemStyle = getFixedItemStyle(itemStyleModel, scale);
  40098. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel, scale);
  40099. var labelModel = regionModel.getModel(labelAccessPath);
  40100. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  40101. var dataIdx;
  40102. // Use the itemStyle in data if has data
  40103. if (data) {
  40104. dataIdx = data.indexOfName(region.name);
  40105. // Only visual color of each item will be used. It can be encoded by dataRange
  40106. // But visual color of series is used in symbol drawing
  40107. //
  40108. // Visual color for each series is for the symbol draw
  40109. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  40110. if (visualColor) {
  40111. itemStyle.fill = visualColor;
  40112. }
  40113. }
  40114. each$1(region.geometries, function (geometry) {
  40115. if (geometry.type !== 'polygon') {
  40116. return;
  40117. }
  40118. compoundPath.shape.paths.push(new Polygon({
  40119. shape: {
  40120. points: geometry.exterior
  40121. }
  40122. }));
  40123. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); i++) {
  40124. compoundPath.shape.paths.push(new Polygon({
  40125. shape: {
  40126. points: geometry.interiors[i]
  40127. }
  40128. }));
  40129. }
  40130. });
  40131. compoundPath.setStyle(itemStyle);
  40132. compoundPath.style.strokeNoScale = true;
  40133. compoundPath.culling = true;
  40134. // Label
  40135. var showLabel = labelModel.get('show');
  40136. var hoverShowLabel = hoverLabelModel.get('show');
  40137. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  40138. var itemLayout = data && data.getItemLayout(dataIdx);
  40139. // In the following cases label will be drawn
  40140. // 1. In map series and data value is NaN
  40141. // 2. In geo component
  40142. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  40143. if (
  40144. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  40145. || (itemLayout && itemLayout.showLabel)
  40146. ) {
  40147. var query = !isGeo ? dataIdx : region.name;
  40148. var labelFetcher;
  40149. // Consider dataIdx not found.
  40150. if (!data || dataIdx >= 0) {
  40151. labelFetcher = mapOrGeoModel;
  40152. }
  40153. var textEl = new Text({
  40154. position: region.center.slice(),
  40155. // FIXME
  40156. // label rotation is not support yet in geo or regions of series-map
  40157. // that has no data. The rotation will be effected by this `scale`.
  40158. // So needed to change to RectText?
  40159. scale: [1 / scale[0], 1 / scale[1]],
  40160. z2: 10,
  40161. silent: true
  40162. });
  40163. setLabelStyle(
  40164. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  40165. {
  40166. labelFetcher: labelFetcher,
  40167. labelDataIndex: query,
  40168. defaultText: region.name,
  40169. useInsideStyle: false
  40170. },
  40171. {
  40172. textAlign: 'center',
  40173. textVerticalAlign: 'middle'
  40174. }
  40175. );
  40176. regionGroup.add(textEl);
  40177. }
  40178. // setItemGraphicEl, setHoverStyle after all polygons and labels
  40179. // are added to the rigionGroup
  40180. if (data) {
  40181. data.setItemGraphicEl(dataIdx, regionGroup);
  40182. }
  40183. else {
  40184. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  40185. // Package custom mouse event for geo component
  40186. compoundPath.eventData = {
  40187. componentType: 'geo',
  40188. componentIndex: mapOrGeoModel.componentIndex,
  40189. geoIndex: mapOrGeoModel.componentIndex,
  40190. name: region.name,
  40191. region: (regionModel && regionModel.option) || {}
  40192. };
  40193. }
  40194. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  40195. groupRegions.push(region);
  40196. setHoverStyle(
  40197. regionGroup,
  40198. hoverItemStyle,
  40199. {hoverSilentOnTouch: !!mapOrGeoModel.get('selectedMode')}
  40200. );
  40201. regionsGroup.add(regionGroup);
  40202. });
  40203. this._updateController(mapOrGeoModel, ecModel, api);
  40204. updateMapSelectHandler(this, mapOrGeoModel, regionsGroup, api, fromView);
  40205. updateMapSelected(mapOrGeoModel, regionsGroup);
  40206. },
  40207. remove: function () {
  40208. this._regionsGroup.removeAll();
  40209. this._backgroundGroup.removeAll();
  40210. this._controller.dispose();
  40211. this._mapName && geoSourceManager.removeGraphic(this._mapName, this.uid);
  40212. this._mapName = null;
  40213. this._controllerHost = {};
  40214. },
  40215. _updateBackground: function (geo) {
  40216. var mapName = geo.map;
  40217. if (this._mapName !== mapName) {
  40218. each$1(geoSourceManager.makeGraphic(mapName, this.uid), function (root) {
  40219. this._backgroundGroup.add(root);
  40220. }, this);
  40221. }
  40222. this._mapName = mapName;
  40223. },
  40224. _updateController: function (mapOrGeoModel, ecModel, api) {
  40225. var geo = mapOrGeoModel.coordinateSystem;
  40226. var controller = this._controller;
  40227. var controllerHost = this._controllerHost;
  40228. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  40229. controllerHost.zoom = geo.getZoom();
  40230. // roamType is will be set default true if it is null
  40231. controller.enable(mapOrGeoModel.get('roam') || false);
  40232. var mainType = mapOrGeoModel.mainType;
  40233. function makeActionBase() {
  40234. var action = {
  40235. type: 'geoRoam',
  40236. componentType: mainType
  40237. };
  40238. action[mainType + 'Id'] = mapOrGeoModel.id;
  40239. return action;
  40240. }
  40241. controller.off('pan').on('pan', function (e) {
  40242. this._mouseDownFlag = false;
  40243. updateViewOnPan(controllerHost, e.dx, e.dy);
  40244. api.dispatchAction(extend(makeActionBase(), {
  40245. dx: e.dx,
  40246. dy: e.dy
  40247. }));
  40248. }, this);
  40249. controller.off('zoom').on('zoom', function (e) {
  40250. this._mouseDownFlag = false;
  40251. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  40252. api.dispatchAction(extend(makeActionBase(), {
  40253. zoom: e.scale,
  40254. originX: e.originX,
  40255. originY: e.originY
  40256. }));
  40257. if (this._updateGroup) {
  40258. var scale = this.group.scale;
  40259. this._regionsGroup.traverse(function (el) {
  40260. if (el.type === 'text') {
  40261. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  40262. }
  40263. });
  40264. }
  40265. }, this);
  40266. controller.setPointerChecker(function (e, x, y) {
  40267. return geo.getViewRectAfterRoam().contain(x, y)
  40268. && !onIrrelevantElement(e, api, mapOrGeoModel);
  40269. });
  40270. }
  40271. };
  40272. /*
  40273. * Licensed to the Apache Software Foundation (ASF) under one
  40274. * or more contributor license agreements. See the NOTICE file
  40275. * distributed with this work for additional information
  40276. * regarding copyright ownership. The ASF licenses this file
  40277. * to you under the Apache License, Version 2.0 (the
  40278. * "License"); you may not use this file except in compliance
  40279. * with the License. You may obtain a copy of the License at
  40280. *
  40281. * http://www.apache.org/licenses/LICENSE-2.0
  40282. *
  40283. * Unless required by applicable law or agreed to in writing,
  40284. * software distributed under the License is distributed on an
  40285. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40286. * KIND, either express or implied. See the License for the
  40287. * specific language governing permissions and limitations
  40288. * under the License.
  40289. */
  40290. var HIGH_DOWN_PROP = '__seriesMapHighDown';
  40291. var RECORD_VERSION_PROP = '__seriesMapCallKey';
  40292. extendChartView({
  40293. type: 'map',
  40294. render: function (mapModel, ecModel, api, payload) {
  40295. // Not render if it is an toggleSelect action from self
  40296. if (payload && payload.type === 'mapToggleSelect'
  40297. && payload.from === this.uid
  40298. ) {
  40299. return;
  40300. }
  40301. var group = this.group;
  40302. group.removeAll();
  40303. if (mapModel.getHostGeoModel()) {
  40304. return;
  40305. }
  40306. // Not update map if it is an roam action from self
  40307. if (!(payload && payload.type === 'geoRoam'
  40308. && payload.componentType === 'series'
  40309. && payload.seriesId === mapModel.id
  40310. )
  40311. ) {
  40312. if (mapModel.needsDrawMap) {
  40313. var mapDraw = this._mapDraw || new MapDraw(api, true);
  40314. group.add(mapDraw.group);
  40315. mapDraw.draw(mapModel, ecModel, api, this, payload);
  40316. this._mapDraw = mapDraw;
  40317. }
  40318. else {
  40319. // Remove drawed map
  40320. this._mapDraw && this._mapDraw.remove();
  40321. this._mapDraw = null;
  40322. }
  40323. }
  40324. else {
  40325. var mapDraw = this._mapDraw;
  40326. mapDraw && group.add(mapDraw.group);
  40327. }
  40328. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  40329. && this._renderSymbols(mapModel, ecModel, api);
  40330. },
  40331. remove: function () {
  40332. this._mapDraw && this._mapDraw.remove();
  40333. this._mapDraw = null;
  40334. this.group.removeAll();
  40335. },
  40336. dispose: function () {
  40337. this._mapDraw && this._mapDraw.remove();
  40338. this._mapDraw = null;
  40339. },
  40340. _renderSymbols: function (mapModel, ecModel, api) {
  40341. var originalData = mapModel.originalData;
  40342. var group = this.group;
  40343. originalData.each(originalData.mapDimension('value'), function (value, originalDataIndex) {
  40344. if (isNaN(value)) {
  40345. return;
  40346. }
  40347. var layout = originalData.getItemLayout(originalDataIndex);
  40348. if (!layout || !layout.point) {
  40349. // Not exists in map
  40350. return;
  40351. }
  40352. var point = layout.point;
  40353. var offset = layout.offset;
  40354. var circle = new Circle({
  40355. style: {
  40356. // Because the special of map draw.
  40357. // Which needs statistic of multiple series and draw on one map.
  40358. // And each series also need a symbol with legend color
  40359. //
  40360. // Layout and visual are put one the different data
  40361. fill: mapModel.getData().getVisual('color')
  40362. },
  40363. shape: {
  40364. cx: point[0] + offset * 9,
  40365. cy: point[1],
  40366. r: 3
  40367. },
  40368. silent: true,
  40369. // Do not overlap the first series, on which labels are displayed.
  40370. z2: 8 + (!offset ? Z2_EMPHASIS_LIFT + 1 : 0)
  40371. });
  40372. // Only the series that has the first value on the same region is in charge of rendering the label.
  40373. // But consider the case:
  40374. // series: [
  40375. // {id: 'X', type: 'map', map: 'm', {data: [{name: 'A', value: 11}, {name: 'B', {value: 22}]},
  40376. // {id: 'Y', type: 'map', map: 'm', {data: [{name: 'A', value: 21}, {name: 'C', {value: 33}]}
  40377. // ]
  40378. // The offset `0` of item `A` is at series `X`, but of item `C` is at series `Y`.
  40379. // For backward compatibility, we follow the rule that render label `A` by the
  40380. // settings on series `X` but render label `C` by the settings on series `Y`.
  40381. if (!offset) {
  40382. var fullData = mapModel.mainSeries.getData();
  40383. var name = originalData.getName(originalDataIndex);
  40384. var fullIndex = fullData.indexOfName(name);
  40385. var itemModel = originalData.getItemModel(originalDataIndex);
  40386. var labelModel = itemModel.getModel('label');
  40387. var hoverLabelModel = itemModel.getModel('emphasis.label');
  40388. var regionGroup = fullData.getItemGraphicEl(fullIndex);
  40389. // `getFormattedLabel` needs to use `getData` inside. Here
  40390. // `mapModel.getData()` is shallow cloned from `mainSeries.getData()`.
  40391. // FIXME
  40392. // If this is not the `mainSeries`, the item model (like label formatter)
  40393. // set on original data item will never get. But it has been working
  40394. // like that from the begining, and this scenario is rarely encountered.
  40395. // So it won't be fixed until have to.
  40396. var normalText = retrieve2(
  40397. mapModel.getFormattedLabel(fullIndex, 'normal'),
  40398. name
  40399. );
  40400. var emphasisText = retrieve2(
  40401. mapModel.getFormattedLabel(fullIndex, 'emphasis'),
  40402. normalText
  40403. );
  40404. var highDownRecord = regionGroup[HIGH_DOWN_PROP];
  40405. var recordVersion = Math.random();
  40406. // Prevent from register listeners duplicatedly when roaming.
  40407. if (!highDownRecord) {
  40408. highDownRecord = regionGroup[HIGH_DOWN_PROP] = {};
  40409. var onEmphasis = curry(onRegionHighDown, true);
  40410. var onNormal = curry(onRegionHighDown, false);
  40411. regionGroup.on('mouseover', onEmphasis)
  40412. .on('mouseout', onNormal)
  40413. .on('emphasis', onEmphasis)
  40414. .on('normal', onNormal);
  40415. }
  40416. // Prevent removed regions effect current grapics.
  40417. regionGroup[RECORD_VERSION_PROP] = recordVersion;
  40418. extend(highDownRecord, {
  40419. recordVersion: recordVersion,
  40420. circle: circle,
  40421. labelModel: labelModel,
  40422. hoverLabelModel: hoverLabelModel,
  40423. emphasisText: emphasisText,
  40424. normalText: normalText
  40425. });
  40426. // FIXME
  40427. // Consider set option when emphasis.
  40428. enterRegionHighDown(highDownRecord, false);
  40429. }
  40430. group.add(circle);
  40431. });
  40432. }
  40433. });
  40434. function onRegionHighDown(toHighOrDown) {
  40435. var highDownRecord = this[HIGH_DOWN_PROP];
  40436. if (highDownRecord && highDownRecord.recordVersion === this[RECORD_VERSION_PROP]) {
  40437. enterRegionHighDown(highDownRecord, toHighOrDown);
  40438. }
  40439. }
  40440. function enterRegionHighDown(highDownRecord, toHighOrDown) {
  40441. var circle = highDownRecord.circle;
  40442. var labelModel = highDownRecord.labelModel;
  40443. var hoverLabelModel = highDownRecord.hoverLabelModel;
  40444. var emphasisText = highDownRecord.emphasisText;
  40445. var normalText = highDownRecord.normalText;
  40446. if (toHighOrDown) {
  40447. circle.style.extendFrom(
  40448. setTextStyle({}, hoverLabelModel, {
  40449. text: hoverLabelModel.get('show') ? emphasisText : null
  40450. }, {isRectText: true, useInsideStyle: false}, true)
  40451. );
  40452. // Make label upper than others if overlaps.
  40453. circle.__mapOriginalZ2 = circle.z2;
  40454. circle.z2 += Z2_EMPHASIS_LIFT;
  40455. }
  40456. else {
  40457. setTextStyle(circle.style, labelModel, {
  40458. text: labelModel.get('show') ? normalText : null,
  40459. textPosition: labelModel.getShallow('position') || 'bottom'
  40460. }, {isRectText: true, useInsideStyle: false});
  40461. // Trigger normalize style like padding.
  40462. circle.dirty(false);
  40463. if (circle.__mapOriginalZ2 != null) {
  40464. circle.z2 = circle.__mapOriginalZ2;
  40465. circle.__mapOriginalZ2 = null;
  40466. }
  40467. }
  40468. }
  40469. /*
  40470. * Licensed to the Apache Software Foundation (ASF) under one
  40471. * or more contributor license agreements. See the NOTICE file
  40472. * distributed with this work for additional information
  40473. * regarding copyright ownership. The ASF licenses this file
  40474. * to you under the Apache License, Version 2.0 (the
  40475. * "License"); you may not use this file except in compliance
  40476. * with the License. You may obtain a copy of the License at
  40477. *
  40478. * http://www.apache.org/licenses/LICENSE-2.0
  40479. *
  40480. * Unless required by applicable law or agreed to in writing,
  40481. * software distributed under the License is distributed on an
  40482. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40483. * KIND, either express or implied. See the License for the
  40484. * specific language governing permissions and limitations
  40485. * under the License.
  40486. */
  40487. /**
  40488. * @param {module:echarts/coord/View} view
  40489. * @param {Object} payload
  40490. * @param {Object} [zoomLimit]
  40491. */
  40492. function updateCenterAndZoom(
  40493. view, payload, zoomLimit
  40494. ) {
  40495. var previousZoom = view.getZoom();
  40496. var center = view.getCenter();
  40497. var zoom = payload.zoom;
  40498. var point = view.dataToPoint(center);
  40499. if (payload.dx != null && payload.dy != null) {
  40500. point[0] -= payload.dx;
  40501. point[1] -= payload.dy;
  40502. var center = view.pointToData(point);
  40503. view.setCenter(center);
  40504. }
  40505. if (zoom != null) {
  40506. if (zoomLimit) {
  40507. var zoomMin = zoomLimit.min || 0;
  40508. var zoomMax = zoomLimit.max || Infinity;
  40509. zoom = Math.max(
  40510. Math.min(previousZoom * zoom, zoomMax),
  40511. zoomMin
  40512. ) / previousZoom;
  40513. }
  40514. // Zoom on given point(originX, originY)
  40515. view.scale[0] *= zoom;
  40516. view.scale[1] *= zoom;
  40517. var position = view.position;
  40518. var fixX = (payload.originX - position[0]) * (zoom - 1);
  40519. var fixY = (payload.originY - position[1]) * (zoom - 1);
  40520. position[0] -= fixX;
  40521. position[1] -= fixY;
  40522. view.updateTransform();
  40523. // Get the new center
  40524. var center = view.pointToData(point);
  40525. view.setCenter(center);
  40526. view.setZoom(zoom * previousZoom);
  40527. }
  40528. return {
  40529. center: view.getCenter(),
  40530. zoom: view.getZoom()
  40531. };
  40532. }
  40533. /*
  40534. * Licensed to the Apache Software Foundation (ASF) under one
  40535. * or more contributor license agreements. See the NOTICE file
  40536. * distributed with this work for additional information
  40537. * regarding copyright ownership. The ASF licenses this file
  40538. * to you under the Apache License, Version 2.0 (the
  40539. * "License"); you may not use this file except in compliance
  40540. * with the License. You may obtain a copy of the License at
  40541. *
  40542. * http://www.apache.org/licenses/LICENSE-2.0
  40543. *
  40544. * Unless required by applicable law or agreed to in writing,
  40545. * software distributed under the License is distributed on an
  40546. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40547. * KIND, either express or implied. See the License for the
  40548. * specific language governing permissions and limitations
  40549. * under the License.
  40550. */
  40551. /**
  40552. * @payload
  40553. * @property {string} [componentType=series]
  40554. * @property {number} [dx]
  40555. * @property {number} [dy]
  40556. * @property {number} [zoom]
  40557. * @property {number} [originX]
  40558. * @property {number} [originY]
  40559. */
  40560. registerAction({
  40561. type: 'geoRoam',
  40562. event: 'geoRoam',
  40563. update: 'updateTransform'
  40564. }, function (payload, ecModel) {
  40565. var componentType = payload.componentType || 'series';
  40566. ecModel.eachComponent(
  40567. { mainType: componentType, query: payload },
  40568. function (componentModel) {
  40569. var geo = componentModel.coordinateSystem;
  40570. if (geo.type !== 'geo') {
  40571. return;
  40572. }
  40573. var res = updateCenterAndZoom(
  40574. geo, payload, componentModel.get('scaleLimit')
  40575. );
  40576. componentModel.setCenter
  40577. && componentModel.setCenter(res.center);
  40578. componentModel.setZoom
  40579. && componentModel.setZoom(res.zoom);
  40580. // All map series with same `map` use the same geo coordinate system
  40581. // So the center and zoom must be in sync. Include the series not selected by legend
  40582. if (componentType === 'series') {
  40583. each$1(componentModel.seriesGroup, function (seriesModel) {
  40584. seriesModel.setCenter(res.center);
  40585. seriesModel.setZoom(res.zoom);
  40586. });
  40587. }
  40588. }
  40589. );
  40590. });
  40591. /*
  40592. * Licensed to the Apache Software Foundation (ASF) under one
  40593. * or more contributor license agreements. See the NOTICE file
  40594. * distributed with this work for additional information
  40595. * regarding copyright ownership. The ASF licenses this file
  40596. * to you under the Apache License, Version 2.0 (the
  40597. * "License"); you may not use this file except in compliance
  40598. * with the License. You may obtain a copy of the License at
  40599. *
  40600. * http://www.apache.org/licenses/LICENSE-2.0
  40601. *
  40602. * Unless required by applicable law or agreed to in writing,
  40603. * software distributed under the License is distributed on an
  40604. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40605. * KIND, either express or implied. See the License for the
  40606. * specific language governing permissions and limitations
  40607. * under the License.
  40608. */
  40609. /**
  40610. * Simple view coordinate system
  40611. * Mapping given x, y to transformd view x, y
  40612. */
  40613. var v2ApplyTransform$1 = applyTransform;
  40614. // Dummy transform node
  40615. function TransformDummy() {
  40616. Transformable.call(this);
  40617. }
  40618. mixin(TransformDummy, Transformable);
  40619. function View(name) {
  40620. /**
  40621. * @type {string}
  40622. */
  40623. this.name = name;
  40624. /**
  40625. * @type {Object}
  40626. */
  40627. this.zoomLimit;
  40628. Transformable.call(this);
  40629. this._roamTransformable = new TransformDummy();
  40630. this._rawTransformable = new TransformDummy();
  40631. this._center;
  40632. this._zoom;
  40633. }
  40634. View.prototype = {
  40635. constructor: View,
  40636. type: 'view',
  40637. /**
  40638. * @param {Array.<string>}
  40639. * @readOnly
  40640. */
  40641. dimensions: ['x', 'y'],
  40642. /**
  40643. * Set bounding rect
  40644. * @param {number} x
  40645. * @param {number} y
  40646. * @param {number} width
  40647. * @param {number} height
  40648. */
  40649. // PENDING to getRect
  40650. setBoundingRect: function (x, y, width, height) {
  40651. this._rect = new BoundingRect(x, y, width, height);
  40652. return this._rect;
  40653. },
  40654. /**
  40655. * @return {module:zrender/core/BoundingRect}
  40656. */
  40657. // PENDING to getRect
  40658. getBoundingRect: function () {
  40659. return this._rect;
  40660. },
  40661. /**
  40662. * @param {number} x
  40663. * @param {number} y
  40664. * @param {number} width
  40665. * @param {number} height
  40666. */
  40667. setViewRect: function (x, y, width, height) {
  40668. this.transformTo(x, y, width, height);
  40669. this._viewRect = new BoundingRect(x, y, width, height);
  40670. },
  40671. /**
  40672. * Transformed to particular position and size
  40673. * @param {number} x
  40674. * @param {number} y
  40675. * @param {number} width
  40676. * @param {number} height
  40677. */
  40678. transformTo: function (x, y, width, height) {
  40679. var rect = this.getBoundingRect();
  40680. var rawTransform = this._rawTransformable;
  40681. rawTransform.transform = rect.calculateTransform(
  40682. new BoundingRect(x, y, width, height)
  40683. );
  40684. rawTransform.decomposeTransform();
  40685. this._updateTransform();
  40686. },
  40687. /**
  40688. * Set center of view
  40689. * @param {Array.<number>} [centerCoord]
  40690. */
  40691. setCenter: function (centerCoord) {
  40692. if (!centerCoord) {
  40693. return;
  40694. }
  40695. this._center = centerCoord;
  40696. this._updateCenterAndZoom();
  40697. },
  40698. /**
  40699. * @param {number} zoom
  40700. */
  40701. setZoom: function (zoom) {
  40702. zoom = zoom || 1;
  40703. var zoomLimit = this.zoomLimit;
  40704. if (zoomLimit) {
  40705. if (zoomLimit.max != null) {
  40706. zoom = Math.min(zoomLimit.max, zoom);
  40707. }
  40708. if (zoomLimit.min != null) {
  40709. zoom = Math.max(zoomLimit.min, zoom);
  40710. }
  40711. }
  40712. this._zoom = zoom;
  40713. this._updateCenterAndZoom();
  40714. },
  40715. /**
  40716. * Get default center without roam
  40717. */
  40718. getDefaultCenter: function () {
  40719. // Rect before any transform
  40720. var rawRect = this.getBoundingRect();
  40721. var cx = rawRect.x + rawRect.width / 2;
  40722. var cy = rawRect.y + rawRect.height / 2;
  40723. return [cx, cy];
  40724. },
  40725. getCenter: function () {
  40726. return this._center || this.getDefaultCenter();
  40727. },
  40728. getZoom: function () {
  40729. return this._zoom || 1;
  40730. },
  40731. /**
  40732. * @return {Array.<number}
  40733. */
  40734. getRoamTransform: function () {
  40735. return this._roamTransformable.getLocalTransform();
  40736. },
  40737. /**
  40738. * Remove roam
  40739. */
  40740. _updateCenterAndZoom: function () {
  40741. // Must update after view transform updated
  40742. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  40743. var roamTransform = this._roamTransformable;
  40744. var defaultCenter = this.getDefaultCenter();
  40745. var center = this.getCenter();
  40746. var zoom = this.getZoom();
  40747. center = applyTransform([], center, rawTransformMatrix);
  40748. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  40749. roamTransform.origin = center;
  40750. roamTransform.position = [
  40751. defaultCenter[0] - center[0],
  40752. defaultCenter[1] - center[1]
  40753. ];
  40754. roamTransform.scale = [zoom, zoom];
  40755. this._updateTransform();
  40756. },
  40757. /**
  40758. * Update transform from roam and mapLocation
  40759. * @private
  40760. */
  40761. _updateTransform: function () {
  40762. var roamTransformable = this._roamTransformable;
  40763. var rawTransformable = this._rawTransformable;
  40764. rawTransformable.parent = roamTransformable;
  40765. roamTransformable.updateTransform();
  40766. rawTransformable.updateTransform();
  40767. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  40768. this._rawTransform = rawTransformable.getLocalTransform();
  40769. this.invTransform = this.invTransform || [];
  40770. invert(this.invTransform, this.transform);
  40771. this.decomposeTransform();
  40772. },
  40773. /**
  40774. * @return {module:zrender/core/BoundingRect}
  40775. */
  40776. getViewRect: function () {
  40777. return this._viewRect;
  40778. },
  40779. /**
  40780. * Get view rect after roam transform
  40781. * @return {module:zrender/core/BoundingRect}
  40782. */
  40783. getViewRectAfterRoam: function () {
  40784. var rect = this.getBoundingRect().clone();
  40785. rect.applyTransform(this.transform);
  40786. return rect;
  40787. },
  40788. /**
  40789. * Convert a single (lon, lat) data item to (x, y) point.
  40790. * @param {Array.<number>} data
  40791. * @param {boolean} noRoam
  40792. * @param {Array.<number>} [out]
  40793. * @return {Array.<number>}
  40794. */
  40795. dataToPoint: function (data, noRoam, out) {
  40796. var transform = noRoam ? this._rawTransform : this.transform;
  40797. out = out || [];
  40798. return transform
  40799. ? v2ApplyTransform$1(out, data, transform)
  40800. : copy(out, data);
  40801. },
  40802. /**
  40803. * Convert a (x, y) point to (lon, lat) data
  40804. * @param {Array.<number>} point
  40805. * @return {Array.<number>}
  40806. */
  40807. pointToData: function (point) {
  40808. var invTransform = this.invTransform;
  40809. return invTransform
  40810. ? v2ApplyTransform$1([], point, invTransform)
  40811. : [point[0], point[1]];
  40812. },
  40813. /**
  40814. * @implements
  40815. * see {module:echarts/CoodinateSystem}
  40816. */
  40817. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  40818. /**
  40819. * @implements
  40820. * see {module:echarts/CoodinateSystem}
  40821. */
  40822. convertFromPixel: curry(doConvert$1, 'pointToData'),
  40823. /**
  40824. * @implements
  40825. * see {module:echarts/CoodinateSystem}
  40826. */
  40827. containPoint: function (point) {
  40828. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  40829. }
  40830. /**
  40831. * @return {number}
  40832. */
  40833. // getScalarScale: function () {
  40834. // // Use determinant square root of transform to mutiply scalar
  40835. // var m = this.transform;
  40836. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  40837. // return det;
  40838. // }
  40839. };
  40840. mixin(View, Transformable);
  40841. function doConvert$1(methodName, ecModel, finder, value) {
  40842. var seriesModel = finder.seriesModel;
  40843. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  40844. return coordSys === this ? coordSys[methodName](value) : null;
  40845. }
  40846. /*
  40847. * Licensed to the Apache Software Foundation (ASF) under one
  40848. * or more contributor license agreements. See the NOTICE file
  40849. * distributed with this work for additional information
  40850. * regarding copyright ownership. The ASF licenses this file
  40851. * to you under the Apache License, Version 2.0 (the
  40852. * "License"); you may not use this file except in compliance
  40853. * with the License. You may obtain a copy of the License at
  40854. *
  40855. * http://www.apache.org/licenses/LICENSE-2.0
  40856. *
  40857. * Unless required by applicable law or agreed to in writing,
  40858. * software distributed under the License is distributed on an
  40859. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40860. * KIND, either express or implied. See the License for the
  40861. * specific language governing permissions and limitations
  40862. * under the License.
  40863. */
  40864. /**
  40865. * [Geo description]
  40866. * For backward compatibility, the orginal interface:
  40867. * `name, map, geoJson, specialAreas, nameMap` is kept.
  40868. *
  40869. * @param {string|Object} name
  40870. * @param {string} map Map type
  40871. * Specify the positioned areas by left, top, width, height
  40872. * @param {Object.<string, string>} [nameMap]
  40873. * Specify name alias
  40874. * @param {boolean} [invertLongitute=true]
  40875. */
  40876. function Geo(name, map$$1, nameMap, invertLongitute) {
  40877. View.call(this, name);
  40878. /**
  40879. * Map type
  40880. * @type {string}
  40881. */
  40882. this.map = map$$1;
  40883. var source = geoSourceManager.load(map$$1, nameMap);
  40884. this._nameCoordMap = source.nameCoordMap;
  40885. this._regionsMap = source.regionsMap;
  40886. this._invertLongitute = invertLongitute == null ? true : invertLongitute;
  40887. /**
  40888. * @readOnly
  40889. */
  40890. this.regions = source.regions;
  40891. /**
  40892. * @type {module:zrender/src/core/BoundingRect}
  40893. */
  40894. this._rect = source.boundingRect;
  40895. }
  40896. Geo.prototype = {
  40897. constructor: Geo,
  40898. type: 'geo',
  40899. /**
  40900. * @param {Array.<string>}
  40901. * @readOnly
  40902. */
  40903. dimensions: ['lng', 'lat'],
  40904. /**
  40905. * If contain given lng,lat coord
  40906. * @param {Array.<number>}
  40907. * @readOnly
  40908. */
  40909. containCoord: function (coord) {
  40910. var regions = this.regions;
  40911. for (var i = 0; i < regions.length; i++) {
  40912. if (regions[i].contain(coord)) {
  40913. return true;
  40914. }
  40915. }
  40916. return false;
  40917. },
  40918. /**
  40919. * @override
  40920. */
  40921. transformTo: function (x, y, width, height) {
  40922. var rect = this.getBoundingRect();
  40923. var invertLongitute = this._invertLongitute;
  40924. rect = rect.clone();
  40925. if (invertLongitute) {
  40926. // Longitute is inverted
  40927. rect.y = -rect.y - rect.height;
  40928. }
  40929. var rawTransformable = this._rawTransformable;
  40930. rawTransformable.transform = rect.calculateTransform(
  40931. new BoundingRect(x, y, width, height)
  40932. );
  40933. rawTransformable.decomposeTransform();
  40934. if (invertLongitute) {
  40935. var scale = rawTransformable.scale;
  40936. scale[1] = -scale[1];
  40937. }
  40938. rawTransformable.updateTransform();
  40939. this._updateTransform();
  40940. },
  40941. /**
  40942. * @param {string} name
  40943. * @return {module:echarts/coord/geo/Region}
  40944. */
  40945. getRegion: function (name) {
  40946. return this._regionsMap.get(name);
  40947. },
  40948. getRegionByCoord: function (coord) {
  40949. var regions = this.regions;
  40950. for (var i = 0; i < regions.length; i++) {
  40951. if (regions[i].contain(coord)) {
  40952. return regions[i];
  40953. }
  40954. }
  40955. },
  40956. /**
  40957. * Add geoCoord for indexing by name
  40958. * @param {string} name
  40959. * @param {Array.<number>} geoCoord
  40960. */
  40961. addGeoCoord: function (name, geoCoord) {
  40962. this._nameCoordMap.set(name, geoCoord);
  40963. },
  40964. /**
  40965. * Get geoCoord by name
  40966. * @param {string} name
  40967. * @return {Array.<number>}
  40968. */
  40969. getGeoCoord: function (name) {
  40970. return this._nameCoordMap.get(name);
  40971. },
  40972. /**
  40973. * @override
  40974. */
  40975. getBoundingRect: function () {
  40976. return this._rect;
  40977. },
  40978. /**
  40979. * @param {string|Array.<number>} data
  40980. * @param {boolean} noRoam
  40981. * @param {Array.<number>} [out]
  40982. * @return {Array.<number>}
  40983. */
  40984. dataToPoint: function (data, noRoam, out) {
  40985. if (typeof data === 'string') {
  40986. // Map area name to geoCoord
  40987. data = this.getGeoCoord(data);
  40988. }
  40989. if (data) {
  40990. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  40991. }
  40992. },
  40993. /**
  40994. * @override
  40995. */
  40996. convertToPixel: curry(doConvert, 'dataToPoint'),
  40997. /**
  40998. * @override
  40999. */
  41000. convertFromPixel: curry(doConvert, 'pointToData')
  41001. };
  41002. mixin(Geo, View);
  41003. function doConvert(methodName, ecModel, finder, value) {
  41004. var geoModel = finder.geoModel;
  41005. var seriesModel = finder.seriesModel;
  41006. var coordSys = geoModel
  41007. ? geoModel.coordinateSystem
  41008. : seriesModel
  41009. ? (
  41010. seriesModel.coordinateSystem // For map.
  41011. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  41012. )
  41013. : null;
  41014. return coordSys === this ? coordSys[methodName](value) : null;
  41015. }
  41016. /*
  41017. * Licensed to the Apache Software Foundation (ASF) under one
  41018. * or more contributor license agreements. See the NOTICE file
  41019. * distributed with this work for additional information
  41020. * regarding copyright ownership. The ASF licenses this file
  41021. * to you under the Apache License, Version 2.0 (the
  41022. * "License"); you may not use this file except in compliance
  41023. * with the License. You may obtain a copy of the License at
  41024. *
  41025. * http://www.apache.org/licenses/LICENSE-2.0
  41026. *
  41027. * Unless required by applicable law or agreed to in writing,
  41028. * software distributed under the License is distributed on an
  41029. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41030. * KIND, either express or implied. See the License for the
  41031. * specific language governing permissions and limitations
  41032. * under the License.
  41033. */
  41034. /**
  41035. * Resize method bound to the geo
  41036. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  41037. * @param {module:echarts/ExtensionAPI} api
  41038. */
  41039. function resizeGeo(geoModel, api) {
  41040. var boundingCoords = geoModel.get('boundingCoords');
  41041. if (boundingCoords != null) {
  41042. var leftTop = boundingCoords[0];
  41043. var rightBottom = boundingCoords[1];
  41044. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  41045. if (__DEV__) {
  41046. console.error('Invalid boundingCoords');
  41047. }
  41048. }
  41049. else {
  41050. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  41051. }
  41052. }
  41053. var rect = this.getBoundingRect();
  41054. var boxLayoutOption;
  41055. var center = geoModel.get('layoutCenter');
  41056. var size = geoModel.get('layoutSize');
  41057. var viewWidth = api.getWidth();
  41058. var viewHeight = api.getHeight();
  41059. var aspect = rect.width / rect.height * this.aspectScale;
  41060. var useCenterAndSize = false;
  41061. if (center && size) {
  41062. center = [
  41063. parsePercent$1(center[0], viewWidth),
  41064. parsePercent$1(center[1], viewHeight)
  41065. ];
  41066. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  41067. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  41068. useCenterAndSize = true;
  41069. }
  41070. else {
  41071. if (__DEV__) {
  41072. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  41073. }
  41074. }
  41075. }
  41076. var viewRect;
  41077. if (useCenterAndSize) {
  41078. var viewRect = {};
  41079. if (aspect > 1) {
  41080. // Width is same with size
  41081. viewRect.width = size;
  41082. viewRect.height = size / aspect;
  41083. }
  41084. else {
  41085. viewRect.height = size;
  41086. viewRect.width = size * aspect;
  41087. }
  41088. viewRect.y = center[1] - viewRect.height / 2;
  41089. viewRect.x = center[0] - viewRect.width / 2;
  41090. }
  41091. else {
  41092. // Use left/top/width/height
  41093. boxLayoutOption = geoModel.getBoxLayoutParams();
  41094. // 0.75 rate
  41095. boxLayoutOption.aspect = aspect;
  41096. viewRect = getLayoutRect(boxLayoutOption, {
  41097. width: viewWidth,
  41098. height: viewHeight
  41099. });
  41100. }
  41101. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  41102. this.setCenter(geoModel.get('center'));
  41103. this.setZoom(geoModel.get('zoom'));
  41104. }
  41105. /**
  41106. * @param {module:echarts/coord/Geo} geo
  41107. * @param {module:echarts/model/Model} model
  41108. * @inner
  41109. */
  41110. function setGeoCoords(geo, model) {
  41111. each$1(model.get('geoCoord'), function (geoCoord, name) {
  41112. geo.addGeoCoord(name, geoCoord);
  41113. });
  41114. }
  41115. var geoCreator = {
  41116. // For deciding which dimensions to use when creating list data
  41117. dimensions: Geo.prototype.dimensions,
  41118. create: function (ecModel, api) {
  41119. var geoList = [];
  41120. // FIXME Create each time may be slow
  41121. ecModel.eachComponent('geo', function (geoModel, idx) {
  41122. var name = geoModel.get('map');
  41123. var aspectScale = geoModel.get('aspectScale');
  41124. var invertLongitute = true;
  41125. var mapRecords = mapDataStorage.retrieveMap(name);
  41126. if (mapRecords && mapRecords[0] && mapRecords[0].type === 'svg') {
  41127. aspectScale == null && (aspectScale = 1);
  41128. invertLongitute = false;
  41129. }
  41130. else {
  41131. aspectScale == null && (aspectScale = 0.75);
  41132. }
  41133. var geo = new Geo(name + idx, name, geoModel.get('nameMap'), invertLongitute);
  41134. geo.aspectScale = aspectScale;
  41135. geo.zoomLimit = geoModel.get('scaleLimit');
  41136. geoList.push(geo);
  41137. setGeoCoords(geo, geoModel);
  41138. geoModel.coordinateSystem = geo;
  41139. geo.model = geoModel;
  41140. // Inject resize method
  41141. geo.resize = resizeGeo;
  41142. geo.resize(geoModel, api);
  41143. });
  41144. ecModel.eachSeries(function (seriesModel) {
  41145. var coordSys = seriesModel.get('coordinateSystem');
  41146. if (coordSys === 'geo') {
  41147. var geoIndex = seriesModel.get('geoIndex') || 0;
  41148. seriesModel.coordinateSystem = geoList[geoIndex];
  41149. }
  41150. });
  41151. // If has map series
  41152. var mapModelGroupBySeries = {};
  41153. ecModel.eachSeriesByType('map', function (seriesModel) {
  41154. if (!seriesModel.getHostGeoModel()) {
  41155. var mapType = seriesModel.getMapType();
  41156. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  41157. mapModelGroupBySeries[mapType].push(seriesModel);
  41158. }
  41159. });
  41160. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  41161. var nameMapList = map(mapSeries, function (singleMapSeries) {
  41162. return singleMapSeries.get('nameMap');
  41163. });
  41164. var geo = new Geo(mapType, mapType, mergeAll(nameMapList));
  41165. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  41166. return singleMapSeries.get('scaleLimit');
  41167. }));
  41168. geoList.push(geo);
  41169. // Inject resize method
  41170. geo.resize = resizeGeo;
  41171. geo.aspectScale = mapSeries[0].get('aspectScale');
  41172. geo.resize(mapSeries[0], api);
  41173. each$1(mapSeries, function (singleMapSeries) {
  41174. singleMapSeries.coordinateSystem = geo;
  41175. setGeoCoords(geo, singleMapSeries);
  41176. });
  41177. });
  41178. return geoList;
  41179. },
  41180. /**
  41181. * Fill given regions array
  41182. * @param {Array.<Object>} originRegionArr
  41183. * @param {string} mapName
  41184. * @param {Object} [nameMap]
  41185. * @return {Array}
  41186. */
  41187. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  41188. // Not use the original
  41189. var regionsArr = (originRegionArr || []).slice();
  41190. var dataNameMap = createHashMap();
  41191. for (var i = 0; i < regionsArr.length; i++) {
  41192. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  41193. }
  41194. var source = geoSourceManager.load(mapName, nameMap);
  41195. each$1(source.regions, function (region) {
  41196. var name = region.name;
  41197. !dataNameMap.get(name) && regionsArr.push({name: name});
  41198. });
  41199. return regionsArr;
  41200. }
  41201. };
  41202. registerCoordinateSystem('geo', geoCreator);
  41203. /*
  41204. * Licensed to the Apache Software Foundation (ASF) under one
  41205. * or more contributor license agreements. See the NOTICE file
  41206. * distributed with this work for additional information
  41207. * regarding copyright ownership. The ASF licenses this file
  41208. * to you under the Apache License, Version 2.0 (the
  41209. * "License"); you may not use this file except in compliance
  41210. * with the License. You may obtain a copy of the License at
  41211. *
  41212. * http://www.apache.org/licenses/LICENSE-2.0
  41213. *
  41214. * Unless required by applicable law or agreed to in writing,
  41215. * software distributed under the License is distributed on an
  41216. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41217. * KIND, either express or implied. See the License for the
  41218. * specific language governing permissions and limitations
  41219. * under the License.
  41220. */
  41221. var mapSymbolLayout = function (ecModel) {
  41222. var processedMapType = {};
  41223. ecModel.eachSeriesByType('map', function (mapSeries) {
  41224. var mapType = mapSeries.getMapType();
  41225. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  41226. return;
  41227. }
  41228. var mapSymbolOffsets = {};
  41229. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  41230. var geo = subMapSeries.coordinateSystem;
  41231. var data = subMapSeries.originalData;
  41232. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  41233. data.each(data.mapDimension('value'), function (value, idx) {
  41234. var name = data.getName(idx);
  41235. var region = geo.getRegion(name);
  41236. // If input series.data is [11, 22, '-'/null/undefined, 44],
  41237. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  41238. // not be drawn. So here must validate if value is NaN.
  41239. if (!region || isNaN(value)) {
  41240. return;
  41241. }
  41242. var offset = mapSymbolOffsets[name] || 0;
  41243. var point = geo.dataToPoint(region.center);
  41244. mapSymbolOffsets[name] = offset + 1;
  41245. data.setItemLayout(idx, {
  41246. point: point,
  41247. offset: offset
  41248. });
  41249. });
  41250. }
  41251. });
  41252. // Show label of those region not has legendSymbol(which is offset 0)
  41253. var data = mapSeries.getData();
  41254. data.each(function (idx) {
  41255. var name = data.getName(idx);
  41256. var layout = data.getItemLayout(idx) || {};
  41257. layout.showLabel = !mapSymbolOffsets[name];
  41258. data.setItemLayout(idx, layout);
  41259. });
  41260. processedMapType[mapType] = true;
  41261. });
  41262. };
  41263. /*
  41264. * Licensed to the Apache Software Foundation (ASF) under one
  41265. * or more contributor license agreements. See the NOTICE file
  41266. * distributed with this work for additional information
  41267. * regarding copyright ownership. The ASF licenses this file
  41268. * to you under the Apache License, Version 2.0 (the
  41269. * "License"); you may not use this file except in compliance
  41270. * with the License. You may obtain a copy of the License at
  41271. *
  41272. * http://www.apache.org/licenses/LICENSE-2.0
  41273. *
  41274. * Unless required by applicable law or agreed to in writing,
  41275. * software distributed under the License is distributed on an
  41276. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41277. * KIND, either express or implied. See the License for the
  41278. * specific language governing permissions and limitations
  41279. * under the License.
  41280. */
  41281. var mapVisual = function (ecModel) {
  41282. ecModel.eachSeriesByType('map', function (seriesModel) {
  41283. var colorList = seriesModel.get('color');
  41284. var itemStyleModel = seriesModel.getModel('itemStyle');
  41285. var areaColor = itemStyleModel.get('areaColor');
  41286. var color = itemStyleModel.get('color')
  41287. || colorList[seriesModel.seriesIndex % colorList.length];
  41288. seriesModel.getData().setVisual({
  41289. 'areaColor': areaColor,
  41290. 'color': color
  41291. });
  41292. });
  41293. };
  41294. /*
  41295. * Licensed to the Apache Software Foundation (ASF) under one
  41296. * or more contributor license agreements. See the NOTICE file
  41297. * distributed with this work for additional information
  41298. * regarding copyright ownership. The ASF licenses this file
  41299. * to you under the Apache License, Version 2.0 (the
  41300. * "License"); you may not use this file except in compliance
  41301. * with the License. You may obtain a copy of the License at
  41302. *
  41303. * http://www.apache.org/licenses/LICENSE-2.0
  41304. *
  41305. * Unless required by applicable law or agreed to in writing,
  41306. * software distributed under the License is distributed on an
  41307. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41308. * KIND, either express or implied. See the License for the
  41309. * specific language governing permissions and limitations
  41310. * under the License.
  41311. */
  41312. // FIXME 公用?
  41313. /**
  41314. * @param {Array.<module:echarts/data/List>} datas
  41315. * @param {string} statisticType 'average' 'sum'
  41316. * @inner
  41317. */
  41318. function dataStatistics(datas, statisticType) {
  41319. var dataNameMap = {};
  41320. each$1(datas, function (data) {
  41321. data.each(data.mapDimension('value'), function (value, idx) {
  41322. // Add prefix to avoid conflict with Object.prototype.
  41323. var mapKey = 'ec-' + data.getName(idx);
  41324. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  41325. if (!isNaN(value)) {
  41326. dataNameMap[mapKey].push(value);
  41327. }
  41328. });
  41329. });
  41330. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  41331. var mapKey = 'ec-' + datas[0].getName(idx);
  41332. var sum = 0;
  41333. var min = Infinity;
  41334. var max = -Infinity;
  41335. var len = dataNameMap[mapKey].length;
  41336. for (var i = 0; i < len; i++) {
  41337. min = Math.min(min, dataNameMap[mapKey][i]);
  41338. max = Math.max(max, dataNameMap[mapKey][i]);
  41339. sum += dataNameMap[mapKey][i];
  41340. }
  41341. var result;
  41342. if (statisticType === 'min') {
  41343. result = min;
  41344. }
  41345. else if (statisticType === 'max') {
  41346. result = max;
  41347. }
  41348. else if (statisticType === 'average') {
  41349. result = sum / len;
  41350. }
  41351. else {
  41352. result = sum;
  41353. }
  41354. return len === 0 ? NaN : result;
  41355. });
  41356. }
  41357. var mapDataStatistic = function (ecModel) {
  41358. var seriesGroups = {};
  41359. ecModel.eachSeriesByType('map', function (seriesModel) {
  41360. var hostGeoModel = seriesModel.getHostGeoModel();
  41361. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  41362. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  41363. });
  41364. each$1(seriesGroups, function (seriesList, key) {
  41365. var data = dataStatistics(
  41366. map(seriesList, function (seriesModel) {
  41367. return seriesModel.getData();
  41368. }),
  41369. seriesList[0].get('mapValueCalculation')
  41370. );
  41371. for (var i = 0; i < seriesList.length; i++) {
  41372. seriesList[i].originalData = seriesList[i].getData();
  41373. }
  41374. // FIXME Put where?
  41375. for (var i = 0; i < seriesList.length; i++) {
  41376. seriesList[i].seriesGroup = seriesList;
  41377. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  41378. seriesList[i].setData(data.cloneShallow());
  41379. seriesList[i].mainSeries = seriesList[0];
  41380. }
  41381. });
  41382. };
  41383. /*
  41384. * Licensed to the Apache Software Foundation (ASF) under one
  41385. * or more contributor license agreements. See the NOTICE file
  41386. * distributed with this work for additional information
  41387. * regarding copyright ownership. The ASF licenses this file
  41388. * to you under the Apache License, Version 2.0 (the
  41389. * "License"); you may not use this file except in compliance
  41390. * with the License. You may obtain a copy of the License at
  41391. *
  41392. * http://www.apache.org/licenses/LICENSE-2.0
  41393. *
  41394. * Unless required by applicable law or agreed to in writing,
  41395. * software distributed under the License is distributed on an
  41396. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41397. * KIND, either express or implied. See the License for the
  41398. * specific language governing permissions and limitations
  41399. * under the License.
  41400. */
  41401. var backwardCompat$2 = function (option) {
  41402. // Save geoCoord
  41403. var mapSeries = [];
  41404. each$1(option.series, function (seriesOpt) {
  41405. if (seriesOpt && seriesOpt.type === 'map') {
  41406. mapSeries.push(seriesOpt);
  41407. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  41408. // Put x, y, width, height, x2, y2 in the top level
  41409. defaults(seriesOpt, seriesOpt.mapLocation);
  41410. }
  41411. });
  41412. };
  41413. /*
  41414. * Licensed to the Apache Software Foundation (ASF) under one
  41415. * or more contributor license agreements. See the NOTICE file
  41416. * distributed with this work for additional information
  41417. * regarding copyright ownership. The ASF licenses this file
  41418. * to you under the Apache License, Version 2.0 (the
  41419. * "License"); you may not use this file except in compliance
  41420. * with the License. You may obtain a copy of the License at
  41421. *
  41422. * http://www.apache.org/licenses/LICENSE-2.0
  41423. *
  41424. * Unless required by applicable law or agreed to in writing,
  41425. * software distributed under the License is distributed on an
  41426. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41427. * KIND, either express or implied. See the License for the
  41428. * specific language governing permissions and limitations
  41429. * under the License.
  41430. */
  41431. registerLayout(mapSymbolLayout);
  41432. registerVisual(mapVisual);
  41433. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  41434. registerPreprocessor(backwardCompat$2);
  41435. createDataSelectAction('map', [{
  41436. type: 'mapToggleSelect',
  41437. event: 'mapselectchanged',
  41438. method: 'toggleSelected'
  41439. }, {
  41440. type: 'mapSelect',
  41441. event: 'mapselected',
  41442. method: 'select'
  41443. }, {
  41444. type: 'mapUnSelect',
  41445. event: 'mapunselected',
  41446. method: 'unSelect'
  41447. }]);
  41448. /*
  41449. * Licensed to the Apache Software Foundation (ASF) under one
  41450. * or more contributor license agreements. See the NOTICE file
  41451. * distributed with this work for additional information
  41452. * regarding copyright ownership. The ASF licenses this file
  41453. * to you under the Apache License, Version 2.0 (the
  41454. * "License"); you may not use this file except in compliance
  41455. * with the License. You may obtain a copy of the License at
  41456. *
  41457. * http://www.apache.org/licenses/LICENSE-2.0
  41458. *
  41459. * Unless required by applicable law or agreed to in writing,
  41460. * software distributed under the License is distributed on an
  41461. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41462. * KIND, either express or implied. See the License for the
  41463. * specific language governing permissions and limitations
  41464. * under the License.
  41465. */
  41466. /**
  41467. * Link lists and struct (graph or tree)
  41468. */
  41469. var each$7 = each$1;
  41470. var DATAS = '\0__link_datas';
  41471. var MAIN_DATA = '\0__link_mainData';
  41472. // Caution:
  41473. // In most case, either list or its shallow clones (see list.cloneShallow)
  41474. // is active in echarts process. So considering heap memory consumption,
  41475. // we do not clone tree or graph, but share them among list and its shallow clones.
  41476. // But in some rare case, we have to keep old list (like do animation in chart). So
  41477. // please take care that both the old list and the new list share the same tree/graph.
  41478. /**
  41479. * @param {Object} opt
  41480. * @param {module:echarts/data/List} opt.mainData
  41481. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  41482. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  41483. * @param {Object} [opt.datas] {dataType: data},
  41484. * like: {node: nodeList, edge: edgeList}.
  41485. * Should contain mainData.
  41486. * @param {Object} [opt.datasAttr] {dataType: attr},
  41487. * designation: struct[datasAttr[dataType]] = list;
  41488. */
  41489. function linkList(opt) {
  41490. var mainData = opt.mainData;
  41491. var datas = opt.datas;
  41492. if (!datas) {
  41493. datas = {main: mainData};
  41494. opt.datasAttr = {main: 'data'};
  41495. }
  41496. opt.datas = opt.mainData = null;
  41497. linkAll(mainData, datas, opt);
  41498. // Porxy data original methods.
  41499. each$7(datas, function (data) {
  41500. each$7(mainData.TRANSFERABLE_METHODS, function (methodName) {
  41501. data.wrapMethod(methodName, curry(transferInjection, opt));
  41502. });
  41503. });
  41504. // Beyond transfer, additional features should be added to `cloneShallow`.
  41505. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  41506. // Only mainData trigger change, because struct.update may trigger
  41507. // another changable methods, which may bring about dead lock.
  41508. each$7(mainData.CHANGABLE_METHODS, function (methodName) {
  41509. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  41510. });
  41511. // Make sure datas contains mainData.
  41512. assert$1(datas[mainData.dataType] === mainData);
  41513. }
  41514. function transferInjection(opt, res) {
  41515. if (isMainData(this)) {
  41516. // Transfer datas to new main data.
  41517. var datas = extend({}, this[DATAS]);
  41518. datas[this.dataType] = res;
  41519. linkAll(res, datas, opt);
  41520. }
  41521. else {
  41522. // Modify the reference in main data to point newData.
  41523. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  41524. }
  41525. return res;
  41526. }
  41527. function changeInjection(opt, res) {
  41528. opt.struct && opt.struct.update(this);
  41529. return res;
  41530. }
  41531. function cloneShallowInjection(opt, res) {
  41532. // cloneShallow, which brings about some fragilities, may be inappropriate
  41533. // to be exposed as an API. So for implementation simplicity we can make
  41534. // the restriction that cloneShallow of not-mainData should not be invoked
  41535. // outside, but only be invoked here.
  41536. each$7(res[DATAS], function (data, dataType) {
  41537. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  41538. });
  41539. return res;
  41540. }
  41541. /**
  41542. * Supplement method to List.
  41543. *
  41544. * @public
  41545. * @param {string} [dataType] If not specified, return mainData.
  41546. * @return {module:echarts/data/List}
  41547. */
  41548. function getLinkedData(dataType) {
  41549. var mainData = this[MAIN_DATA];
  41550. return (dataType == null || mainData == null)
  41551. ? mainData
  41552. : mainData[DATAS][dataType];
  41553. }
  41554. function isMainData(data) {
  41555. return data[MAIN_DATA] === data;
  41556. }
  41557. function linkAll(mainData, datas, opt) {
  41558. mainData[DATAS] = {};
  41559. each$7(datas, function (data, dataType) {
  41560. linkSingle(data, dataType, mainData, opt);
  41561. });
  41562. }
  41563. function linkSingle(data, dataType, mainData, opt) {
  41564. mainData[DATAS][dataType] = data;
  41565. data[MAIN_DATA] = mainData;
  41566. data.dataType = dataType;
  41567. if (opt.struct) {
  41568. data[opt.structAttr] = opt.struct;
  41569. opt.struct[opt.datasAttr[dataType]] = data;
  41570. }
  41571. // Supplement method.
  41572. data.getLinkedData = getLinkedData;
  41573. }
  41574. /*
  41575. * Licensed to the Apache Software Foundation (ASF) under one
  41576. * or more contributor license agreements. See the NOTICE file
  41577. * distributed with this work for additional information
  41578. * regarding copyright ownership. The ASF licenses this file
  41579. * to you under the Apache License, Version 2.0 (the
  41580. * "License"); you may not use this file except in compliance
  41581. * with the License. You may obtain a copy of the License at
  41582. *
  41583. * http://www.apache.org/licenses/LICENSE-2.0
  41584. *
  41585. * Unless required by applicable law or agreed to in writing,
  41586. * software distributed under the License is distributed on an
  41587. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41588. * KIND, either express or implied. See the License for the
  41589. * specific language governing permissions and limitations
  41590. * under the License.
  41591. */
  41592. /**
  41593. * Tree data structure
  41594. *
  41595. * @module echarts/data/Tree
  41596. */
  41597. /**
  41598. * @constructor module:echarts/data/Tree~TreeNode
  41599. * @param {string} name
  41600. * @param {module:echarts/data/Tree} hostTree
  41601. */
  41602. var TreeNode = function (name, hostTree) {
  41603. /**
  41604. * @type {string}
  41605. */
  41606. this.name = name || '';
  41607. /**
  41608. * Depth of node
  41609. *
  41610. * @type {number}
  41611. * @readOnly
  41612. */
  41613. this.depth = 0;
  41614. /**
  41615. * Height of the subtree rooted at this node.
  41616. * @type {number}
  41617. * @readOnly
  41618. */
  41619. this.height = 0;
  41620. /**
  41621. * @type {module:echarts/data/Tree~TreeNode}
  41622. * @readOnly
  41623. */
  41624. this.parentNode = null;
  41625. /**
  41626. * Reference to list item.
  41627. * Do not persistent dataIndex outside,
  41628. * besause it may be changed by list.
  41629. * If dataIndex -1,
  41630. * this node is logical deleted (filtered) in list.
  41631. *
  41632. * @type {Object}
  41633. * @readOnly
  41634. */
  41635. this.dataIndex = -1;
  41636. /**
  41637. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  41638. * @readOnly
  41639. */
  41640. this.children = [];
  41641. /**
  41642. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  41643. * @pubilc
  41644. */
  41645. this.viewChildren = [];
  41646. /**
  41647. * @type {moduel:echarts/data/Tree}
  41648. * @readOnly
  41649. */
  41650. this.hostTree = hostTree;
  41651. };
  41652. TreeNode.prototype = {
  41653. constructor: TreeNode,
  41654. /**
  41655. * The node is removed.
  41656. * @return {boolean} is removed.
  41657. */
  41658. isRemoved: function () {
  41659. return this.dataIndex < 0;
  41660. },
  41661. /**
  41662. * Travel this subtree (include this node).
  41663. * Usage:
  41664. * node.eachNode(function () { ... }); // preorder
  41665. * node.eachNode('preorder', function () { ... }); // preorder
  41666. * node.eachNode('postorder', function () { ... }); // postorder
  41667. * node.eachNode(
  41668. * {order: 'postorder', attr: 'viewChildren'},
  41669. * function () { ... }
  41670. * ); // postorder
  41671. *
  41672. * @param {(Object|string)} options If string, means order.
  41673. * @param {string=} options.order 'preorder' or 'postorder'
  41674. * @param {string=} options.attr 'children' or 'viewChildren'
  41675. * @param {Function} cb If in preorder and return false,
  41676. * its subtree will not be visited.
  41677. * @param {Object} [context]
  41678. */
  41679. eachNode: function (options, cb, context) {
  41680. if (typeof options === 'function') {
  41681. context = cb;
  41682. cb = options;
  41683. options = null;
  41684. }
  41685. options = options || {};
  41686. if (isString(options)) {
  41687. options = {order: options};
  41688. }
  41689. var order = options.order || 'preorder';
  41690. var children = this[options.attr || 'children'];
  41691. var suppressVisitSub;
  41692. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  41693. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  41694. children[i].eachNode(options, cb, context);
  41695. }
  41696. order === 'postorder' && cb.call(context, this);
  41697. },
  41698. /**
  41699. * Update depth and height of this subtree.
  41700. *
  41701. * @param {number} depth
  41702. */
  41703. updateDepthAndHeight: function (depth) {
  41704. var height = 0;
  41705. this.depth = depth;
  41706. for (var i = 0; i < this.children.length; i++) {
  41707. var child = this.children[i];
  41708. child.updateDepthAndHeight(depth + 1);
  41709. if (child.height > height) {
  41710. height = child.height;
  41711. }
  41712. }
  41713. this.height = height + 1;
  41714. },
  41715. /**
  41716. * @param {string} id
  41717. * @return {module:echarts/data/Tree~TreeNode}
  41718. */
  41719. getNodeById: function (id) {
  41720. if (this.getId() === id) {
  41721. return this;
  41722. }
  41723. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  41724. var res = children[i].getNodeById(id);
  41725. if (res) {
  41726. return res;
  41727. }
  41728. }
  41729. },
  41730. /**
  41731. * @param {module:echarts/data/Tree~TreeNode} node
  41732. * @return {boolean}
  41733. */
  41734. contains: function (node) {
  41735. if (node === this) {
  41736. return true;
  41737. }
  41738. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  41739. var res = children[i].contains(node);
  41740. if (res) {
  41741. return res;
  41742. }
  41743. }
  41744. },
  41745. /**
  41746. * @param {boolean} includeSelf Default false.
  41747. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  41748. */
  41749. getAncestors: function (includeSelf) {
  41750. var ancestors = [];
  41751. var node = includeSelf ? this : this.parentNode;
  41752. while (node) {
  41753. ancestors.push(node);
  41754. node = node.parentNode;
  41755. }
  41756. ancestors.reverse();
  41757. return ancestors;
  41758. },
  41759. /**
  41760. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  41761. * @return {number} Value.
  41762. */
  41763. getValue: function (dimension) {
  41764. var data = this.hostTree.data;
  41765. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  41766. },
  41767. /**
  41768. * @param {Object} layout
  41769. * @param {boolean=} [merge=false]
  41770. */
  41771. setLayout: function (layout, merge$$1) {
  41772. this.dataIndex >= 0
  41773. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  41774. },
  41775. /**
  41776. * @return {Object} layout
  41777. */
  41778. getLayout: function () {
  41779. return this.hostTree.data.getItemLayout(this.dataIndex);
  41780. },
  41781. /**
  41782. * @param {string} [path]
  41783. * @return {module:echarts/model/Model}
  41784. */
  41785. getModel: function (path) {
  41786. if (this.dataIndex < 0) {
  41787. return;
  41788. }
  41789. var hostTree = this.hostTree;
  41790. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  41791. var levelModel = this.getLevelModel();
  41792. var leavesModel;
  41793. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  41794. leavesModel = this.getLeavesModel();
  41795. }
  41796. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  41797. },
  41798. /**
  41799. * @return {module:echarts/model/Model}
  41800. */
  41801. getLevelModel: function () {
  41802. return (this.hostTree.levelModels || [])[this.depth];
  41803. },
  41804. /**
  41805. * @return {module:echarts/model/Model}
  41806. */
  41807. getLeavesModel: function () {
  41808. return this.hostTree.leavesModel;
  41809. },
  41810. /**
  41811. * @example
  41812. * setItemVisual('color', color);
  41813. * setItemVisual({
  41814. * 'color': color
  41815. * });
  41816. */
  41817. setVisual: function (key, value) {
  41818. this.dataIndex >= 0
  41819. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  41820. },
  41821. /**
  41822. * Get item visual
  41823. */
  41824. getVisual: function (key, ignoreParent) {
  41825. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  41826. },
  41827. /**
  41828. * @public
  41829. * @return {number}
  41830. */
  41831. getRawIndex: function () {
  41832. return this.hostTree.data.getRawIndex(this.dataIndex);
  41833. },
  41834. /**
  41835. * @public
  41836. * @return {string}
  41837. */
  41838. getId: function () {
  41839. return this.hostTree.data.getId(this.dataIndex);
  41840. },
  41841. /**
  41842. * if this is an ancestor of another node
  41843. *
  41844. * @public
  41845. * @param {TreeNode} node another node
  41846. * @return {boolean} if is ancestor
  41847. */
  41848. isAncestorOf: function (node) {
  41849. var parent = node.parentNode;
  41850. while (parent) {
  41851. if (parent === this) {
  41852. return true;
  41853. }
  41854. parent = parent.parentNode;
  41855. }
  41856. return false;
  41857. },
  41858. /**
  41859. * if this is an descendant of another node
  41860. *
  41861. * @public
  41862. * @param {TreeNode} node another node
  41863. * @return {boolean} if is descendant
  41864. */
  41865. isDescendantOf: function (node) {
  41866. return node !== this && node.isAncestorOf(this);
  41867. }
  41868. };
  41869. /**
  41870. * @constructor
  41871. * @alias module:echarts/data/Tree
  41872. * @param {module:echarts/model/Model} hostModel
  41873. * @param {Array.<Object>} levelOptions
  41874. * @param {Object} leavesOption
  41875. */
  41876. function Tree(hostModel, levelOptions, leavesOption) {
  41877. /**
  41878. * @type {module:echarts/data/Tree~TreeNode}
  41879. * @readOnly
  41880. */
  41881. this.root;
  41882. /**
  41883. * @type {module:echarts/data/List}
  41884. * @readOnly
  41885. */
  41886. this.data;
  41887. /**
  41888. * Index of each item is the same as the raw index of coresponding list item.
  41889. * @private
  41890. * @type {Array.<module:echarts/data/Tree~TreeNode}
  41891. */
  41892. this._nodes = [];
  41893. /**
  41894. * @private
  41895. * @readOnly
  41896. * @type {module:echarts/model/Model}
  41897. */
  41898. this.hostModel = hostModel;
  41899. /**
  41900. * @private
  41901. * @readOnly
  41902. * @type {Array.<module:echarts/model/Model}
  41903. */
  41904. this.levelModels = map(levelOptions || [], function (levelDefine) {
  41905. return new Model(levelDefine, hostModel, hostModel.ecModel);
  41906. });
  41907. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  41908. }
  41909. Tree.prototype = {
  41910. constructor: Tree,
  41911. type: 'tree',
  41912. /**
  41913. * Travel this subtree (include this node).
  41914. * Usage:
  41915. * node.eachNode(function () { ... }); // preorder
  41916. * node.eachNode('preorder', function () { ... }); // preorder
  41917. * node.eachNode('postorder', function () { ... }); // postorder
  41918. * node.eachNode(
  41919. * {order: 'postorder', attr: 'viewChildren'},
  41920. * function () { ... }
  41921. * ); // postorder
  41922. *
  41923. * @param {(Object|string)} options If string, means order.
  41924. * @param {string=} options.order 'preorder' or 'postorder'
  41925. * @param {string=} options.attr 'children' or 'viewChildren'
  41926. * @param {Function} cb
  41927. * @param {Object} [context]
  41928. */
  41929. eachNode: function (options, cb, context) {
  41930. this.root.eachNode(options, cb, context);
  41931. },
  41932. /**
  41933. * @param {number} dataIndex
  41934. * @return {module:echarts/data/Tree~TreeNode}
  41935. */
  41936. getNodeByDataIndex: function (dataIndex) {
  41937. var rawIndex = this.data.getRawIndex(dataIndex);
  41938. return this._nodes[rawIndex];
  41939. },
  41940. /**
  41941. * @param {string} name
  41942. * @return {module:echarts/data/Tree~TreeNode}
  41943. */
  41944. getNodeByName: function (name) {
  41945. return this.root.getNodeByName(name);
  41946. },
  41947. /**
  41948. * Update item available by list,
  41949. * when list has been performed options like 'filterSelf' or 'map'.
  41950. */
  41951. update: function () {
  41952. var data = this.data;
  41953. var nodes = this._nodes;
  41954. for (var i = 0, len = nodes.length; i < len; i++) {
  41955. nodes[i].dataIndex = -1;
  41956. }
  41957. for (var i = 0, len = data.count(); i < len; i++) {
  41958. nodes[data.getRawIndex(i)].dataIndex = i;
  41959. }
  41960. },
  41961. /**
  41962. * Clear all layouts
  41963. */
  41964. clearLayouts: function () {
  41965. this.data.clearItemLayouts();
  41966. }
  41967. };
  41968. /**
  41969. * data node format:
  41970. * {
  41971. * name: ...
  41972. * value: ...
  41973. * children: [
  41974. * {
  41975. * name: ...
  41976. * value: ...
  41977. * children: ...
  41978. * },
  41979. * ...
  41980. * ]
  41981. * }
  41982. *
  41983. * @static
  41984. * @param {Object} dataRoot Root node.
  41985. * @param {module:echarts/model/Model} hostModel
  41986. * @param {Object} treeOptions
  41987. * @param {Array.<Object>} treeOptions.levels
  41988. * @param {Array.<Object>} treeOptions.leaves
  41989. * @return module:echarts/data/Tree
  41990. */
  41991. Tree.createTree = function (dataRoot, hostModel, treeOptions) {
  41992. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  41993. var listData = [];
  41994. var dimMax = 1;
  41995. buildHierarchy(dataRoot);
  41996. function buildHierarchy(dataNode, parentNode) {
  41997. var value = dataNode.value;
  41998. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  41999. listData.push(dataNode);
  42000. var node = new TreeNode(dataNode.name, tree);
  42001. parentNode
  42002. ? addChild(node, parentNode)
  42003. : (tree.root = node);
  42004. tree._nodes.push(node);
  42005. var children = dataNode.children;
  42006. if (children) {
  42007. for (var i = 0; i < children.length; i++) {
  42008. buildHierarchy(children[i], node);
  42009. }
  42010. }
  42011. }
  42012. tree.root.updateDepthAndHeight(0);
  42013. var dimensionsInfo = createDimensions(listData, {
  42014. coordDimensions: ['value'],
  42015. dimensionsCount: dimMax
  42016. });
  42017. var list = new List(dimensionsInfo, hostModel);
  42018. list.initData(listData);
  42019. linkList({
  42020. mainData: list,
  42021. struct: tree,
  42022. structAttr: 'tree'
  42023. });
  42024. tree.update();
  42025. return tree;
  42026. };
  42027. /**
  42028. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  42029. * so this function is not ready and not necessary to be public.
  42030. *
  42031. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  42032. */
  42033. function addChild(child, node) {
  42034. var children = node.children;
  42035. if (child.parentNode === node) {
  42036. return;
  42037. }
  42038. children.push(child);
  42039. child.parentNode = node;
  42040. }
  42041. /*
  42042. * Licensed to the Apache Software Foundation (ASF) under one
  42043. * or more contributor license agreements. See the NOTICE file
  42044. * distributed with this work for additional information
  42045. * regarding copyright ownership. The ASF licenses this file
  42046. * to you under the Apache License, Version 2.0 (the
  42047. * "License"); you may not use this file except in compliance
  42048. * with the License. You may obtain a copy of the License at
  42049. *
  42050. * http://www.apache.org/licenses/LICENSE-2.0
  42051. *
  42052. * Unless required by applicable law or agreed to in writing,
  42053. * software distributed under the License is distributed on an
  42054. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42055. * KIND, either express or implied. See the License for the
  42056. * specific language governing permissions and limitations
  42057. * under the License.
  42058. */
  42059. /**
  42060. * @file Create data struct and define tree view's series model
  42061. * @author Deqing Li(annong035@gmail.com)
  42062. */
  42063. SeriesModel.extend({
  42064. type: 'series.tree',
  42065. layoutInfo: null,
  42066. // can support the position parameters 'left', 'top','right','bottom', 'width',
  42067. // 'height' in the setOption() with 'merge' mode normal.
  42068. layoutMode: 'box',
  42069. /**
  42070. * Init a tree data structure from data in option series
  42071. * @param {Object} option the object used to config echarts view
  42072. * @return {module:echarts/data/List} storage initial data
  42073. */
  42074. getInitialData: function (option) {
  42075. //create an virtual root
  42076. var root = {name: option.name, children: option.data};
  42077. var leaves = option.leaves || {};
  42078. var treeOption = {};
  42079. treeOption.leaves = leaves;
  42080. var tree = Tree.createTree(root, this, treeOption);
  42081. var treeDepth = 0;
  42082. tree.eachNode('preorder', function (node) {
  42083. if (node.depth > treeDepth) {
  42084. treeDepth = node.depth;
  42085. }
  42086. });
  42087. var expandAndCollapse = option.expandAndCollapse;
  42088. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  42089. ? option.initialTreeDepth : treeDepth;
  42090. tree.root.eachNode('preorder', function (node) {
  42091. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  42092. // Add item.collapsed != null, because users can collapse node original in the series.data.
  42093. node.isExpand = (item && item.collapsed != null)
  42094. ? !item.collapsed
  42095. : node.depth <= expandTreeDepth;
  42096. });
  42097. return tree.data;
  42098. },
  42099. /**
  42100. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  42101. * @returns {string} orient
  42102. */
  42103. getOrient: function () {
  42104. var orient = this.get('orient');
  42105. if (orient === 'horizontal') {
  42106. orient = 'LR';
  42107. }
  42108. else if (orient === 'vertical') {
  42109. orient = 'TB';
  42110. }
  42111. return orient;
  42112. },
  42113. setZoom: function (zoom) {
  42114. this.option.zoom = zoom;
  42115. },
  42116. setCenter: function (center) {
  42117. this.option.center = center;
  42118. },
  42119. /**
  42120. * @override
  42121. * @param {number} dataIndex
  42122. */
  42123. formatTooltip: function (dataIndex) {
  42124. var tree = this.getData().tree;
  42125. var realRoot = tree.root.children[0];
  42126. var node = tree.getNodeByDataIndex(dataIndex);
  42127. var value = node.getValue();
  42128. var name = node.name;
  42129. while (node && (node !== realRoot)) {
  42130. name = node.parentNode.name + '.' + name;
  42131. node = node.parentNode;
  42132. }
  42133. return encodeHTML(name + (
  42134. (isNaN(value) || value == null) ? '' : ' : ' + value
  42135. ));
  42136. },
  42137. defaultOption: {
  42138. zlevel: 0,
  42139. z: 2,
  42140. coordinateSystem: 'view',
  42141. // the position of the whole view
  42142. left: '12%',
  42143. top: '12%',
  42144. right: '12%',
  42145. bottom: '12%',
  42146. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  42147. layout: 'orthogonal',
  42148. roam: false, // true | false | 'move' | 'scale', see module:component/helper/RoamController.
  42149. // Symbol size scale ratio in roam
  42150. nodeScaleRatio: 0.4,
  42151. // Default on center of graph
  42152. center: null,
  42153. zoom: 1,
  42154. // The orient of orthoginal layout, can be setted to 'LR', 'TB', 'RL', 'BT'.
  42155. // and the backward compatibility configuration 'horizontal = LR', 'vertical = TB'.
  42156. orient: 'LR',
  42157. symbol: 'emptyCircle',
  42158. symbolSize: 7,
  42159. expandAndCollapse: true,
  42160. initialTreeDepth: 2,
  42161. lineStyle: {
  42162. color: '#ccc',
  42163. width: 1.5,
  42164. curveness: 0.5
  42165. },
  42166. itemStyle: {
  42167. color: 'lightsteelblue',
  42168. borderColor: '#c23531',
  42169. borderWidth: 1.5
  42170. },
  42171. label: {
  42172. show: true,
  42173. color: '#555'
  42174. },
  42175. leaves: {
  42176. label: {
  42177. show: true
  42178. }
  42179. },
  42180. animationEasing: 'linear',
  42181. animationDuration: 700,
  42182. animationDurationUpdate: 1000
  42183. }
  42184. });
  42185. /*
  42186. * Licensed to the Apache Software Foundation (ASF) under one
  42187. * or more contributor license agreements. See the NOTICE file
  42188. * distributed with this work for additional information
  42189. * regarding copyright ownership. The ASF licenses this file
  42190. * to you under the Apache License, Version 2.0 (the
  42191. * "License"); you may not use this file except in compliance
  42192. * with the License. You may obtain a copy of the License at
  42193. *
  42194. * http://www.apache.org/licenses/LICENSE-2.0
  42195. *
  42196. * Unless required by applicable law or agreed to in writing,
  42197. * software distributed under the License is distributed on an
  42198. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42199. * KIND, either express or implied. See the License for the
  42200. * specific language governing permissions and limitations
  42201. * under the License.
  42202. */
  42203. /*
  42204. * A third-party license is embeded for some of the code in this file:
  42205. * The tree layoutHelper implementation was originally copied from
  42206. * "d3.js"(https://github.com/d3/d3-hierarchy) with
  42207. * some modifications made for this project.
  42208. * (see more details in the comment of the specific method below.)
  42209. * The use of the source code of this file is also subject to the terms
  42210. * and consitions of the licence of "d3.js" (BSD-3Clause, see
  42211. * </licenses/LICENSE-d3>).
  42212. */
  42213. /**
  42214. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  42215. * the tree.
  42216. */
  42217. /**
  42218. * Initialize all computational message for following algorithm.
  42219. *
  42220. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree.
  42221. */
  42222. function init$2(root) {
  42223. root.hierNode = {
  42224. defaultAncestor: null,
  42225. ancestor: root,
  42226. prelim: 0,
  42227. modifier: 0,
  42228. change: 0,
  42229. shift: 0,
  42230. i: 0,
  42231. thread: null
  42232. };
  42233. var nodes = [root];
  42234. var node;
  42235. var children;
  42236. while (node = nodes.pop()) { // jshint ignore:line
  42237. children = node.children;
  42238. if (node.isExpand && children.length) {
  42239. var n = children.length;
  42240. for (var i = n - 1; i >= 0; i--) {
  42241. var child = children[i];
  42242. child.hierNode = {
  42243. defaultAncestor: null,
  42244. ancestor: child,
  42245. prelim: 0,
  42246. modifier: 0,
  42247. change: 0,
  42248. shift: 0,
  42249. i: i,
  42250. thread: null
  42251. };
  42252. nodes.push(child);
  42253. }
  42254. }
  42255. }
  42256. }
  42257. /**
  42258. * The implementation of this function was originally copied from "d3.js"
  42259. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  42260. * with some modifications made for this program.
  42261. * See the license statement at the head of this file.
  42262. *
  42263. * Computes a preliminary x coordinate for node. Before that, this function is
  42264. * applied recursively to the children of node, as well as the function
  42265. * apportion(). After spacing out the children by calling executeShifts(), the
  42266. * node is placed to the midpoint of its outermost children.
  42267. *
  42268. * @param {module:echarts/data/Tree~TreeNode} node
  42269. * @param {Function} separation
  42270. */
  42271. function firstWalk(node, separation) {
  42272. var children = node.isExpand ? node.children : [];
  42273. var siblings = node.parentNode.children;
  42274. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null;
  42275. if (children.length) {
  42276. executeShifts(node);
  42277. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  42278. if (subtreeW) {
  42279. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  42280. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  42281. }
  42282. else {
  42283. node.hierNode.prelim = midPoint;
  42284. }
  42285. }
  42286. else if (subtreeW) {
  42287. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  42288. }
  42289. node.parentNode.hierNode.defaultAncestor = apportion(
  42290. node,
  42291. subtreeW,
  42292. node.parentNode.hierNode.defaultAncestor || siblings[0],
  42293. separation
  42294. );
  42295. }
  42296. /**
  42297. * The implementation of this function was originally copied from "d3.js"
  42298. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  42299. * with some modifications made for this program.
  42300. * See the license statement at the head of this file.
  42301. *
  42302. * Computes all real x-coordinates by summing up the modifiers recursively.
  42303. *
  42304. * @param {module:echarts/data/Tree~TreeNode} node
  42305. */
  42306. function secondWalk(node) {
  42307. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  42308. node.setLayout({x: nodeX}, true);
  42309. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  42310. }
  42311. function separation(cb) {
  42312. return arguments.length ? cb : defaultSeparation;
  42313. }
  42314. /**
  42315. * Transform the common coordinate to radial coordinate.
  42316. *
  42317. * @param {number} x
  42318. * @param {number} y
  42319. * @return {Object}
  42320. */
  42321. function radialCoordinate(x, y) {
  42322. var radialCoor = {};
  42323. x -= Math.PI / 2;
  42324. radialCoor.x = y * Math.cos(x);
  42325. radialCoor.y = y * Math.sin(x);
  42326. return radialCoor;
  42327. }
  42328. /**
  42329. * Get the layout position of the whole view.
  42330. *
  42331. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  42332. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  42333. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  42334. */
  42335. function getViewRect(seriesModel, api) {
  42336. return getLayoutRect(
  42337. seriesModel.getBoxLayoutParams(), {
  42338. width: api.getWidth(),
  42339. height: api.getHeight()
  42340. }
  42341. );
  42342. }
  42343. /**
  42344. * All other shifts, applied to the smaller subtrees between w- and w+, are
  42345. * performed by this function.
  42346. *
  42347. * The implementation of this function was originally copied from "d3.js"
  42348. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  42349. * with some modifications made for this program.
  42350. * See the license statement at the head of this file.
  42351. *
  42352. * @param {module:echarts/data/Tree~TreeNode} node
  42353. */
  42354. function executeShifts(node) {
  42355. var children = node.children;
  42356. var n = children.length;
  42357. var shift = 0;
  42358. var change = 0;
  42359. while (--n >= 0) {
  42360. var child = children[n];
  42361. child.hierNode.prelim += shift;
  42362. child.hierNode.modifier += shift;
  42363. change += child.hierNode.change;
  42364. shift += child.hierNode.shift + change;
  42365. }
  42366. }
  42367. /**
  42368. * The implementation of this function was originally copied from "d3.js"
  42369. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  42370. * with some modifications made for this program.
  42371. * See the license statement at the head of this file.
  42372. *
  42373. * The core of the algorithm. Here, a new subtree is combined with the
  42374. * previous subtrees. Threads are used to traverse the inside and outside
  42375. * contours of the left and right subtree up to the highest common level.
  42376. * Whenever two nodes of the inside contours conflict, we compute the left
  42377. * one of the greatest uncommon ancestors using the function nextAncestor()
  42378. * and call moveSubtree() to shift the subtree and prepare the shifts of
  42379. * smaller subtrees. Finally, we add a new thread (if necessary).
  42380. *
  42381. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  42382. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  42383. * @param {module:echarts/data/Tree~TreeNode} ancestor
  42384. * @param {Function} separation
  42385. * @return {module:echarts/data/Tree~TreeNode}
  42386. */
  42387. function apportion(subtreeV, subtreeW, ancestor, separation) {
  42388. if (subtreeW) {
  42389. var nodeOutRight = subtreeV;
  42390. var nodeInRight = subtreeV;
  42391. var nodeOutLeft = nodeInRight.parentNode.children[0];
  42392. var nodeInLeft = subtreeW;
  42393. var sumOutRight = nodeOutRight.hierNode.modifier;
  42394. var sumInRight = nodeInRight.hierNode.modifier;
  42395. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  42396. var sumInLeft = nodeInLeft.hierNode.modifier;
  42397. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  42398. nodeOutRight = nextRight(nodeOutRight);
  42399. nodeOutLeft = nextLeft(nodeOutLeft);
  42400. nodeOutRight.hierNode.ancestor = subtreeV;
  42401. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  42402. - sumInRight + separation(nodeInLeft, nodeInRight);
  42403. if (shift > 0) {
  42404. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  42405. sumInRight += shift;
  42406. sumOutRight += shift;
  42407. }
  42408. sumInLeft += nodeInLeft.hierNode.modifier;
  42409. sumInRight += nodeInRight.hierNode.modifier;
  42410. sumOutRight += nodeOutRight.hierNode.modifier;
  42411. sumOutLeft += nodeOutLeft.hierNode.modifier;
  42412. }
  42413. if (nodeInLeft && !nextRight(nodeOutRight)) {
  42414. nodeOutRight.hierNode.thread = nodeInLeft;
  42415. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  42416. }
  42417. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  42418. nodeOutLeft.hierNode.thread = nodeInRight;
  42419. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  42420. ancestor = subtreeV;
  42421. }
  42422. }
  42423. return ancestor;
  42424. }
  42425. /**
  42426. * This function is used to traverse the right contour of a subtree.
  42427. * It returns the rightmost child of node or the thread of node. The function
  42428. * returns null if and only if node is on the highest depth of its subtree.
  42429. *
  42430. * @param {module:echarts/data/Tree~TreeNode} node
  42431. * @return {module:echarts/data/Tree~TreeNode}
  42432. */
  42433. function nextRight(node) {
  42434. var children = node.children;
  42435. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  42436. }
  42437. /**
  42438. * This function is used to traverse the left contour of a subtree (or a subforest).
  42439. * It returns the leftmost child of node or the thread of node. The function
  42440. * returns null if and only if node is on the highest depth of its subtree.
  42441. *
  42442. * @param {module:echarts/data/Tree~TreeNode} node
  42443. * @return {module:echarts/data/Tree~TreeNode}
  42444. */
  42445. function nextLeft(node) {
  42446. var children = node.children;
  42447. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  42448. }
  42449. /**
  42450. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  42451. * Otherwise, returns the specified ancestor.
  42452. *
  42453. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  42454. * @param {module:echarts/data/Tree~TreeNode} node
  42455. * @param {module:echarts/data/Tree~TreeNode} ancestor
  42456. * @return {module:echarts/data/Tree~TreeNode}
  42457. */
  42458. function nextAncestor(nodeInLeft, node, ancestor) {
  42459. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  42460. ? nodeInLeft.hierNode.ancestor : ancestor;
  42461. }
  42462. /**
  42463. * The implementation of this function was originally copied from "d3.js"
  42464. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  42465. * with some modifications made for this program.
  42466. * See the license statement at the head of this file.
  42467. *
  42468. * Shifts the current subtree rooted at wr.
  42469. * This is done by increasing prelim(w+) and modifier(w+) by shift.
  42470. *
  42471. * @param {module:echarts/data/Tree~TreeNode} wl
  42472. * @param {module:echarts/data/Tree~TreeNode} wr
  42473. * @param {number} shift [description]
  42474. */
  42475. function moveSubtree(wl, wr, shift) {
  42476. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  42477. wr.hierNode.change -= change;
  42478. wr.hierNode.shift += shift;
  42479. wr.hierNode.modifier += shift;
  42480. wr.hierNode.prelim += shift;
  42481. wl.hierNode.change += change;
  42482. }
  42483. /**
  42484. * The implementation of this function was originally copied from "d3.js"
  42485. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  42486. * with some modifications made for this program.
  42487. * See the license statement at the head of this file.
  42488. */
  42489. function defaultSeparation(node1, node2) {
  42490. return node1.parentNode === node2.parentNode ? 1 : 2;
  42491. }
  42492. /*
  42493. * Licensed to the Apache Software Foundation (ASF) under one
  42494. * or more contributor license agreements. See the NOTICE file
  42495. * distributed with this work for additional information
  42496. * regarding copyright ownership. The ASF licenses this file
  42497. * to you under the Apache License, Version 2.0 (the
  42498. * "License"); you may not use this file except in compliance
  42499. * with the License. You may obtain a copy of the License at
  42500. *
  42501. * http://www.apache.org/licenses/LICENSE-2.0
  42502. *
  42503. * Unless required by applicable law or agreed to in writing,
  42504. * software distributed under the License is distributed on an
  42505. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42506. * KIND, either express or implied. See the License for the
  42507. * specific language governing permissions and limitations
  42508. * under the License.
  42509. */
  42510. /**
  42511. * @file This file used to draw tree view.
  42512. * @author Deqing Li(annong035@gmail.com)
  42513. */
  42514. extendChartView({
  42515. type: 'tree',
  42516. /**
  42517. * Init the chart
  42518. * @override
  42519. * @param {module:echarts/model/Global} ecModel
  42520. * @param {module:echarts/ExtensionAPI} api
  42521. */
  42522. init: function (ecModel, api) {
  42523. /**
  42524. * @private
  42525. * @type {module:echarts/data/Tree}
  42526. */
  42527. this._oldTree;
  42528. /**
  42529. * @private
  42530. * @type {module:zrender/container/Group}
  42531. */
  42532. this._mainGroup = new Group();
  42533. /**
  42534. * @private
  42535. * @type {module:echarts/componet/helper/RoamController}
  42536. */
  42537. this._controller = new RoamController(api.getZr());
  42538. this._controllerHost = {target: this.group};
  42539. this.group.add(this._mainGroup);
  42540. },
  42541. render: function (seriesModel, ecModel, api, payload) {
  42542. var data = seriesModel.getData();
  42543. var layoutInfo = seriesModel.layoutInfo;
  42544. var group = this._mainGroup;
  42545. var layout = seriesModel.get('layout');
  42546. if (layout === 'radial') {
  42547. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  42548. }
  42549. else {
  42550. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  42551. }
  42552. this._updateViewCoordSys(seriesModel);
  42553. this._updateController(seriesModel, ecModel, api);
  42554. var oldData = this._data;
  42555. var seriesScope = {
  42556. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  42557. layout: layout,
  42558. orient: seriesModel.getOrient(),
  42559. curvature: seriesModel.get('lineStyle.curveness'),
  42560. symbolRotate: seriesModel.get('symbolRotate'),
  42561. symbolOffset: seriesModel.get('symbolOffset'),
  42562. hoverAnimation: seriesModel.get('hoverAnimation'),
  42563. useNameLabel: true,
  42564. fadeIn: true
  42565. };
  42566. data.diff(oldData)
  42567. .add(function (newIdx) {
  42568. if (symbolNeedsDraw$1(data, newIdx)) {
  42569. // Create node and edge
  42570. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  42571. }
  42572. })
  42573. .update(function (newIdx, oldIdx) {
  42574. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  42575. if (!symbolNeedsDraw$1(data, newIdx)) {
  42576. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  42577. return;
  42578. }
  42579. // Update node and edge
  42580. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  42581. })
  42582. .remove(function (oldIdx) {
  42583. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  42584. // When remove a collapsed node of subtree, since the collapsed
  42585. // node haven't been initialized with a symbol element,
  42586. // you can't found it's symbol element through index.
  42587. // so if we want to remove the symbol element we should insure
  42588. // that the symbol element is not null.
  42589. if (symbolEl) {
  42590. removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  42591. }
  42592. })
  42593. .execute();
  42594. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  42595. this._updateNodeAndLinkScale(seriesModel);
  42596. if (seriesScope.expandAndCollapse === true) {
  42597. data.eachItemGraphicEl(function (el, dataIndex) {
  42598. el.off('click').on('click', function () {
  42599. api.dispatchAction({
  42600. type: 'treeExpandAndCollapse',
  42601. seriesId: seriesModel.id,
  42602. dataIndex: dataIndex
  42603. });
  42604. });
  42605. });
  42606. }
  42607. this._data = data;
  42608. },
  42609. _updateViewCoordSys: function (seriesModel) {
  42610. var data = seriesModel.getData();
  42611. var points = [];
  42612. data.each(function (idx) {
  42613. var layout = data.getItemLayout(idx);
  42614. if (layout && !isNaN(layout.x) && !isNaN(layout.y)) {
  42615. points.push([+layout.x, +layout.y]);
  42616. }
  42617. });
  42618. var min = [];
  42619. var max = [];
  42620. fromPoints(points, min, max);
  42621. // If width or height is 0
  42622. if (max[0] - min[0] === 0) {
  42623. max[0] += 1;
  42624. min[0] -= 1;
  42625. }
  42626. if (max[1] - min[1] === 0) {
  42627. max[1] += 1;
  42628. min[1] -= 1;
  42629. }
  42630. var viewCoordSys = seriesModel.coordinateSystem = new View();
  42631. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  42632. viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  42633. viewCoordSys.setCenter(seriesModel.get('center'));
  42634. viewCoordSys.setZoom(seriesModel.get('zoom'));
  42635. // Here we use viewCoordSys just for computing the 'position' and 'scale' of the group
  42636. this.group.attr({
  42637. position: viewCoordSys.position,
  42638. scale: viewCoordSys.scale
  42639. });
  42640. this._viewCoordSys = viewCoordSys;
  42641. },
  42642. _updateController: function (seriesModel, ecModel, api) {
  42643. var controller = this._controller;
  42644. var controllerHost = this._controllerHost;
  42645. var group = this.group;
  42646. controller.setPointerChecker(function (e, x, y) {
  42647. var rect = group.getBoundingRect();
  42648. rect.applyTransform(group.transform);
  42649. return rect.contain(x, y)
  42650. && !onIrrelevantElement(e, api, seriesModel);
  42651. });
  42652. controller.enable(seriesModel.get('roam'));
  42653. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  42654. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  42655. controller
  42656. .off('pan')
  42657. .off('zoom')
  42658. .on('pan', function (e) {
  42659. updateViewOnPan(controllerHost, e.dx, e.dy);
  42660. api.dispatchAction({
  42661. seriesId: seriesModel.id,
  42662. type: 'treeRoam',
  42663. dx: e.dx,
  42664. dy: e.dy
  42665. });
  42666. }, this)
  42667. .on('zoom', function (e) {
  42668. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  42669. api.dispatchAction({
  42670. seriesId: seriesModel.id,
  42671. type: 'treeRoam',
  42672. zoom: e.scale,
  42673. originX: e.originX,
  42674. originY: e.originY
  42675. });
  42676. this._updateNodeAndLinkScale(seriesModel);
  42677. }, this);
  42678. },
  42679. _updateNodeAndLinkScale: function (seriesModel) {
  42680. var data = seriesModel.getData();
  42681. var nodeScale = this._getNodeGlobalScale(seriesModel);
  42682. var invScale = [nodeScale, nodeScale];
  42683. data.eachItemGraphicEl(function (el, idx) {
  42684. el.attr('scale', invScale);
  42685. });
  42686. },
  42687. _getNodeGlobalScale: function (seriesModel) {
  42688. var coordSys = seriesModel.coordinateSystem;
  42689. if (coordSys.type !== 'view') {
  42690. return 1;
  42691. }
  42692. var nodeScaleRatio = this._nodeScaleRatio;
  42693. var groupScale = coordSys.scale;
  42694. var groupZoom = (groupScale && groupScale[0]) || 1;
  42695. // Scale node when zoom changes
  42696. var roamZoom = coordSys.getZoom();
  42697. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  42698. return nodeScale / groupZoom;
  42699. },
  42700. dispose: function () {
  42701. this._controller && this._controller.dispose();
  42702. this._controllerHost = {};
  42703. },
  42704. remove: function () {
  42705. this._mainGroup.removeAll();
  42706. this._data = null;
  42707. }
  42708. });
  42709. function symbolNeedsDraw$1(data, dataIndex) {
  42710. var layout = data.getItemLayout(dataIndex);
  42711. return layout
  42712. && !isNaN(layout.x) && !isNaN(layout.y)
  42713. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  42714. }
  42715. function getTreeNodeStyle(node, itemModel, seriesScope) {
  42716. seriesScope.itemModel = itemModel;
  42717. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  42718. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  42719. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  42720. seriesScope.labelModel = itemModel.getModel('label');
  42721. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  42722. if (node.isExpand === false && node.children.length !== 0) {
  42723. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  42724. }
  42725. else {
  42726. seriesScope.symbolInnerColor = '#fff';
  42727. }
  42728. return seriesScope;
  42729. }
  42730. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  42731. var isInit = !symbolEl;
  42732. var node = data.tree.getNodeByDataIndex(dataIndex);
  42733. var itemModel = node.getModel();
  42734. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  42735. var virtualRoot = data.tree.root;
  42736. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  42737. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  42738. var sourceLayout = source.getLayout();
  42739. var sourceOldLayout = sourceSymbolEl
  42740. ? {
  42741. x: sourceSymbolEl.position[0],
  42742. y: sourceSymbolEl.position[1],
  42743. rawX: sourceSymbolEl.__radialOldRawX,
  42744. rawY: sourceSymbolEl.__radialOldRawY
  42745. }
  42746. : sourceLayout;
  42747. var targetLayout = node.getLayout();
  42748. if (isInit) {
  42749. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  42750. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  42751. }
  42752. else {
  42753. symbolEl.updateData(data, dataIndex, seriesScope);
  42754. }
  42755. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  42756. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  42757. symbolEl.__radialRawX = targetLayout.rawX;
  42758. symbolEl.__radialRawY = targetLayout.rawY;
  42759. group.add(symbolEl);
  42760. data.setItemGraphicEl(dataIndex, symbolEl);
  42761. updateProps(symbolEl, {
  42762. position: [targetLayout.x, targetLayout.y]
  42763. }, seriesModel);
  42764. var symbolPath = symbolEl.getSymbolPath();
  42765. if (seriesScope.layout === 'radial') {
  42766. var realRoot = virtualRoot.children[0];
  42767. var rootLayout = realRoot.getLayout();
  42768. var length = realRoot.children.length;
  42769. var rad;
  42770. var isLeft;
  42771. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  42772. var center = {};
  42773. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  42774. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  42775. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  42776. if (rad < 0) {
  42777. rad = Math.PI * 2 + rad;
  42778. }
  42779. isLeft = center.x < rootLayout.x;
  42780. if (isLeft) {
  42781. rad = rad - Math.PI;
  42782. }
  42783. }
  42784. else {
  42785. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  42786. if (rad < 0) {
  42787. rad = Math.PI * 2 + rad;
  42788. }
  42789. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  42790. isLeft = targetLayout.x < rootLayout.x;
  42791. if (isLeft) {
  42792. rad = rad - Math.PI;
  42793. }
  42794. }
  42795. else {
  42796. isLeft = targetLayout.x > rootLayout.x;
  42797. if (!isLeft) {
  42798. rad = rad - Math.PI;
  42799. }
  42800. }
  42801. }
  42802. var textPosition = isLeft ? 'left' : 'right';
  42803. symbolPath.setStyle({
  42804. textPosition: textPosition,
  42805. textRotation: -rad,
  42806. textOrigin: 'center',
  42807. verticalAlign: 'middle'
  42808. });
  42809. }
  42810. if (node.parentNode && node.parentNode !== virtualRoot) {
  42811. var edge = symbolEl.__edge;
  42812. if (!edge) {
  42813. edge = symbolEl.__edge = new BezierCurve({
  42814. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  42815. style: defaults({opacity: 0, strokeNoScale: true}, seriesScope.lineStyle)
  42816. });
  42817. }
  42818. updateProps(edge, {
  42819. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  42820. style: {opacity: 1}
  42821. }, seriesModel);
  42822. group.add(edge);
  42823. }
  42824. }
  42825. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  42826. var node = data.tree.getNodeByDataIndex(dataIndex);
  42827. var virtualRoot = data.tree.root;
  42828. var itemModel = node.getModel();
  42829. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  42830. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  42831. var sourceLayout;
  42832. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  42833. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  42834. }
  42835. updateProps(symbolEl, {
  42836. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  42837. }, seriesModel, function () {
  42838. group.remove(symbolEl);
  42839. data.setItemGraphicEl(dataIndex, null);
  42840. });
  42841. symbolEl.fadeOut(null, {keepLabel: true});
  42842. var edge = symbolEl.__edge;
  42843. if (edge) {
  42844. updateProps(edge, {
  42845. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  42846. style: {
  42847. opacity: 0
  42848. }
  42849. }, seriesModel, function () {
  42850. group.remove(edge);
  42851. });
  42852. }
  42853. }
  42854. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  42855. var cpx1;
  42856. var cpy1;
  42857. var cpx2;
  42858. var cpy2;
  42859. var orient = seriesScope.orient;
  42860. var x1;
  42861. var x2;
  42862. var y1;
  42863. var y2;
  42864. if (seriesScope.layout === 'radial') {
  42865. x1 = sourceLayout.rawX;
  42866. y1 = sourceLayout.rawY;
  42867. x2 = targetLayout.rawX;
  42868. y2 = targetLayout.rawY;
  42869. var radialCoor1 = radialCoordinate(x1, y1);
  42870. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  42871. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  42872. var radialCoor4 = radialCoordinate(x2, y2);
  42873. return {
  42874. x1: radialCoor1.x,
  42875. y1: radialCoor1.y,
  42876. x2: radialCoor4.x,
  42877. y2: radialCoor4.y,
  42878. cpx1: radialCoor2.x,
  42879. cpy1: radialCoor2.y,
  42880. cpx2: radialCoor3.x,
  42881. cpy2: radialCoor3.y
  42882. };
  42883. }
  42884. else {
  42885. x1 = sourceLayout.x;
  42886. y1 = sourceLayout.y;
  42887. x2 = targetLayout.x;
  42888. y2 = targetLayout.y;
  42889. if (orient === 'LR' || orient === 'RL') {
  42890. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  42891. cpy1 = y1;
  42892. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  42893. cpy2 = y2;
  42894. }
  42895. if (orient === 'TB' || orient === 'BT') {
  42896. cpx1 = x1;
  42897. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  42898. cpx2 = x2;
  42899. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  42900. }
  42901. }
  42902. return {
  42903. x1: x1,
  42904. y1: y1,
  42905. x2: x2,
  42906. y2: y2,
  42907. cpx1: cpx1,
  42908. cpy1: cpy1,
  42909. cpx2: cpx2,
  42910. cpy2: cpy2
  42911. };
  42912. }
  42913. /*
  42914. * Licensed to the Apache Software Foundation (ASF) under one
  42915. * or more contributor license agreements. See the NOTICE file
  42916. * distributed with this work for additional information
  42917. * regarding copyright ownership. The ASF licenses this file
  42918. * to you under the Apache License, Version 2.0 (the
  42919. * "License"); you may not use this file except in compliance
  42920. * with the License. You may obtain a copy of the License at
  42921. *
  42922. * http://www.apache.org/licenses/LICENSE-2.0
  42923. *
  42924. * Unless required by applicable law or agreed to in writing,
  42925. * software distributed under the License is distributed on an
  42926. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42927. * KIND, either express or implied. See the License for the
  42928. * specific language governing permissions and limitations
  42929. * under the License.
  42930. */
  42931. /**
  42932. * @file Register the actions of the tree
  42933. * @author Deqing Li(annong035@gmail.com)
  42934. */
  42935. registerAction({
  42936. type: 'treeExpandAndCollapse',
  42937. event: 'treeExpandAndCollapse',
  42938. update: 'update'
  42939. }, function (payload, ecModel) {
  42940. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  42941. var dataIndex = payload.dataIndex;
  42942. var tree = seriesModel.getData().tree;
  42943. var node = tree.getNodeByDataIndex(dataIndex);
  42944. node.isExpand = !node.isExpand;
  42945. });
  42946. });
  42947. registerAction({
  42948. type: 'treeRoam',
  42949. event: 'treeRoam',
  42950. // Here we set 'none' instead of 'update', because roam action
  42951. // just need to update the transform matrix without having to recalculate
  42952. // the layout. So don't need to go through the whole update process, such
  42953. // as 'dataPrcocess', 'coordSystemUpdate', 'layout' and so on.
  42954. update: 'none'
  42955. }, function (payload, ecModel) {
  42956. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  42957. var coordSys = seriesModel.coordinateSystem;
  42958. var res = updateCenterAndZoom(coordSys, payload);
  42959. seriesModel.setCenter
  42960. && seriesModel.setCenter(res.center);
  42961. seriesModel.setZoom
  42962. && seriesModel.setZoom(res.zoom);
  42963. });
  42964. });
  42965. /*
  42966. * Licensed to the Apache Software Foundation (ASF) under one
  42967. * or more contributor license agreements. See the NOTICE file
  42968. * distributed with this work for additional information
  42969. * regarding copyright ownership. The ASF licenses this file
  42970. * to you under the Apache License, Version 2.0 (the
  42971. * "License"); you may not use this file except in compliance
  42972. * with the License. You may obtain a copy of the License at
  42973. *
  42974. * http://www.apache.org/licenses/LICENSE-2.0
  42975. *
  42976. * Unless required by applicable law or agreed to in writing,
  42977. * software distributed under the License is distributed on an
  42978. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42979. * KIND, either express or implied. See the License for the
  42980. * specific language governing permissions and limitations
  42981. * under the License.
  42982. */
  42983. /**
  42984. * Traverse the tree from bottom to top and do something
  42985. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  42986. * @param {Function} callback
  42987. */
  42988. function eachAfter(root, callback, separation) {
  42989. var nodes = [root];
  42990. var next = [];
  42991. var node;
  42992. while (node = nodes.pop()) { // jshint ignore:line
  42993. next.push(node);
  42994. if (node.isExpand) {
  42995. var children = node.children;
  42996. if (children.length) {
  42997. for (var i = 0; i < children.length; i++) {
  42998. nodes.push(children[i]);
  42999. }
  43000. }
  43001. }
  43002. }
  43003. while (node = next.pop()) { // jshint ignore:line
  43004. callback(node, separation);
  43005. }
  43006. }
  43007. /**
  43008. * Traverse the tree from top to bottom and do something
  43009. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  43010. * @param {Function} callback
  43011. */
  43012. function eachBefore(root, callback) {
  43013. var nodes = [root];
  43014. var node;
  43015. while (node = nodes.pop()) { // jshint ignore:line
  43016. callback(node);
  43017. if (node.isExpand) {
  43018. var children = node.children;
  43019. if (children.length) {
  43020. for (var i = children.length - 1; i >= 0; i--) {
  43021. nodes.push(children[i]);
  43022. }
  43023. }
  43024. }
  43025. }
  43026. }
  43027. /*
  43028. * Licensed to the Apache Software Foundation (ASF) under one
  43029. * or more contributor license agreements. See the NOTICE file
  43030. * distributed with this work for additional information
  43031. * regarding copyright ownership. The ASF licenses this file
  43032. * to you under the Apache License, Version 2.0 (the
  43033. * "License"); you may not use this file except in compliance
  43034. * with the License. You may obtain a copy of the License at
  43035. *
  43036. * http://www.apache.org/licenses/LICENSE-2.0
  43037. *
  43038. * Unless required by applicable law or agreed to in writing,
  43039. * software distributed under the License is distributed on an
  43040. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43041. * KIND, either express or implied. See the License for the
  43042. * specific language governing permissions and limitations
  43043. * under the License.
  43044. */
  43045. var treeLayout = function (ecModel, api) {
  43046. ecModel.eachSeriesByType('tree', function (seriesModel) {
  43047. commonLayout(seriesModel, api);
  43048. });
  43049. };
  43050. function commonLayout(seriesModel, api) {
  43051. var layoutInfo = getViewRect(seriesModel, api);
  43052. seriesModel.layoutInfo = layoutInfo;
  43053. var layout = seriesModel.get('layout');
  43054. var width = 0;
  43055. var height = 0;
  43056. var separation$$1 = null;
  43057. if (layout === 'radial') {
  43058. width = 2 * Math.PI;
  43059. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  43060. separation$$1 = separation(function (node1, node2) {
  43061. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  43062. });
  43063. }
  43064. else {
  43065. width = layoutInfo.width;
  43066. height = layoutInfo.height;
  43067. separation$$1 = separation();
  43068. }
  43069. var virtualRoot = seriesModel.getData().tree.root;
  43070. var realRoot = virtualRoot.children[0];
  43071. if (realRoot) {
  43072. init$2(virtualRoot);
  43073. eachAfter(realRoot, firstWalk, separation$$1);
  43074. virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim;
  43075. eachBefore(realRoot, secondWalk);
  43076. var left = realRoot;
  43077. var right = realRoot;
  43078. var bottom = realRoot;
  43079. eachBefore(realRoot, function (node) {
  43080. var x = node.getLayout().x;
  43081. if (x < left.getLayout().x) {
  43082. left = node;
  43083. }
  43084. if (x > right.getLayout().x) {
  43085. right = node;
  43086. }
  43087. if (node.depth > bottom.depth) {
  43088. bottom = node;
  43089. }
  43090. });
  43091. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  43092. var tx = delta - left.getLayout().x;
  43093. var kx = 0;
  43094. var ky = 0;
  43095. var coorX = 0;
  43096. var coorY = 0;
  43097. if (layout === 'radial') {
  43098. kx = width / (right.getLayout().x + delta + tx);
  43099. // here we use (node.depth - 1), bucause the real root's depth is 1
  43100. ky = height / ((bottom.depth - 1) || 1);
  43101. eachBefore(realRoot, function (node) {
  43102. coorX = (node.getLayout().x + tx) * kx;
  43103. coorY = (node.depth - 1) * ky;
  43104. var finalCoor = radialCoordinate(coorX, coorY);
  43105. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  43106. });
  43107. }
  43108. else {
  43109. var orient = seriesModel.getOrient();
  43110. if (orient === 'RL' || orient === 'LR') {
  43111. ky = height / (right.getLayout().x + delta + tx);
  43112. kx = width / ((bottom.depth - 1) || 1);
  43113. eachBefore(realRoot, function (node) {
  43114. coorY = (node.getLayout().x + tx) * ky;
  43115. coorX = orient === 'LR'
  43116. ? (node.depth - 1) * kx
  43117. : width - (node.depth - 1) * kx;
  43118. node.setLayout({x: coorX, y: coorY}, true);
  43119. });
  43120. }
  43121. else if (orient === 'TB' || orient === 'BT') {
  43122. kx = width / (right.getLayout().x + delta + tx);
  43123. ky = height / ((bottom.depth - 1) || 1);
  43124. eachBefore(realRoot, function (node) {
  43125. coorX = (node.getLayout().x + tx) * kx;
  43126. coorY = orient === 'TB'
  43127. ? (node.depth - 1) * ky
  43128. : height - (node.depth - 1) * ky;
  43129. node.setLayout({x: coorX, y: coorY}, true);
  43130. });
  43131. }
  43132. }
  43133. }
  43134. }
  43135. /*
  43136. * Licensed to the Apache Software Foundation (ASF) under one
  43137. * or more contributor license agreements. See the NOTICE file
  43138. * distributed with this work for additional information
  43139. * regarding copyright ownership. The ASF licenses this file
  43140. * to you under the Apache License, Version 2.0 (the
  43141. * "License"); you may not use this file except in compliance
  43142. * with the License. You may obtain a copy of the License at
  43143. *
  43144. * http://www.apache.org/licenses/LICENSE-2.0
  43145. *
  43146. * Unless required by applicable law or agreed to in writing,
  43147. * software distributed under the License is distributed on an
  43148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43149. * KIND, either express or implied. See the License for the
  43150. * specific language governing permissions and limitations
  43151. * under the License.
  43152. */
  43153. registerVisual(visualSymbol('tree', 'circle'));
  43154. registerLayout(treeLayout);
  43155. /*
  43156. * Licensed to the Apache Software Foundation (ASF) under one
  43157. * or more contributor license agreements. See the NOTICE file
  43158. * distributed with this work for additional information
  43159. * regarding copyright ownership. The ASF licenses this file
  43160. * to you under the Apache License, Version 2.0 (the
  43161. * "License"); you may not use this file except in compliance
  43162. * with the License. You may obtain a copy of the License at
  43163. *
  43164. * http://www.apache.org/licenses/LICENSE-2.0
  43165. *
  43166. * Unless required by applicable law or agreed to in writing,
  43167. * software distributed under the License is distributed on an
  43168. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43169. * KIND, either express or implied. See the License for the
  43170. * specific language governing permissions and limitations
  43171. * under the License.
  43172. */
  43173. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  43174. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  43175. var root = seriesModel.getData().tree.root;
  43176. var targetNode = payload.targetNode;
  43177. if (typeof targetNode === 'string') {
  43178. targetNode = root.getNodeById(targetNode);
  43179. }
  43180. if (targetNode && root.contains(targetNode)) {
  43181. return {node: targetNode};
  43182. }
  43183. var targetNodeId = payload.targetNodeId;
  43184. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  43185. return {node: targetNode};
  43186. }
  43187. }
  43188. }
  43189. // Not includes the given node at the last item.
  43190. function getPathToRoot(node) {
  43191. var path = [];
  43192. while (node) {
  43193. node = node.parentNode;
  43194. node && path.push(node);
  43195. }
  43196. return path.reverse();
  43197. }
  43198. function aboveViewRoot(viewRoot, node) {
  43199. var viewPath = getPathToRoot(viewRoot);
  43200. return indexOf(viewPath, node) >= 0;
  43201. }
  43202. // From root to the input node (the input node will be included).
  43203. function wrapTreePathInfo(node, seriesModel) {
  43204. var treePathInfo = [];
  43205. while (node) {
  43206. var nodeDataIndex = node.dataIndex;
  43207. treePathInfo.push({
  43208. name: node.name,
  43209. dataIndex: nodeDataIndex,
  43210. value: seriesModel.getRawValue(nodeDataIndex)
  43211. });
  43212. node = node.parentNode;
  43213. }
  43214. treePathInfo.reverse();
  43215. return treePathInfo;
  43216. }
  43217. /*
  43218. * Licensed to the Apache Software Foundation (ASF) under one
  43219. * or more contributor license agreements. See the NOTICE file
  43220. * distributed with this work for additional information
  43221. * regarding copyright ownership. The ASF licenses this file
  43222. * to you under the Apache License, Version 2.0 (the
  43223. * "License"); you may not use this file except in compliance
  43224. * with the License. You may obtain a copy of the License at
  43225. *
  43226. * http://www.apache.org/licenses/LICENSE-2.0
  43227. *
  43228. * Unless required by applicable law or agreed to in writing,
  43229. * software distributed under the License is distributed on an
  43230. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43231. * KIND, either express or implied. See the License for the
  43232. * specific language governing permissions and limitations
  43233. * under the License.
  43234. */
  43235. SeriesModel.extend({
  43236. type: 'series.treemap',
  43237. layoutMode: 'box',
  43238. dependencies: ['grid', 'polar'],
  43239. /**
  43240. * @type {module:echarts/data/Tree~Node}
  43241. */
  43242. _viewRoot: null,
  43243. defaultOption: {
  43244. // Disable progressive rendering
  43245. progressive: 0,
  43246. hoverLayerThreshold: Infinity,
  43247. // center: ['50%', '50%'], // not supported in ec3.
  43248. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  43249. left: 'center',
  43250. top: 'middle',
  43251. right: null,
  43252. bottom: null,
  43253. width: '80%',
  43254. height: '80%',
  43255. sort: true, // Can be null or false or true
  43256. // (order by desc default, asc not supported yet (strange effect))
  43257. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  43258. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  43259. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  43260. // Count from zero (zero represents only view root).
  43261. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  43262. // to align specialized icon. ▷▶❒❐▼✚
  43263. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  43264. // target node area in the view area.
  43265. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  43266. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  43267. // If leafDepth is set and clicking a node which has children but
  43268. // be on left depth, the behaviour would be changing root. Otherwise
  43269. // use behavious defined above.
  43270. animation: true,
  43271. animationDurationUpdate: 900,
  43272. animationEasing: 'quinticInOut',
  43273. breadcrumb: {
  43274. show: true,
  43275. height: 22,
  43276. left: 'center',
  43277. top: 'bottom',
  43278. // right
  43279. // bottom
  43280. emptyItemWidth: 25, // Width of empty node.
  43281. itemStyle: {
  43282. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  43283. borderColor: 'rgba(255,255,255,0.7)',
  43284. borderWidth: 1,
  43285. shadowColor: 'rgba(150,150,150,1)',
  43286. shadowBlur: 3,
  43287. shadowOffsetX: 0,
  43288. shadowOffsetY: 0,
  43289. textStyle: {
  43290. color: '#fff'
  43291. }
  43292. },
  43293. emphasis: {
  43294. textStyle: {}
  43295. }
  43296. },
  43297. label: {
  43298. show: true,
  43299. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  43300. distance: 0,
  43301. padding: 5,
  43302. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  43303. // formatter: null,
  43304. color: '#fff',
  43305. ellipsis: true
  43306. // align
  43307. // verticalAlign
  43308. },
  43309. upperLabel: { // Label when node is parent.
  43310. show: false,
  43311. position: [0, '50%'],
  43312. height: 20,
  43313. // formatter: null,
  43314. color: '#fff',
  43315. ellipsis: true,
  43316. // align: null,
  43317. verticalAlign: 'middle'
  43318. },
  43319. itemStyle: {
  43320. color: null, // Can be 'none' if not necessary.
  43321. colorAlpha: null, // Can be 'none' if not necessary.
  43322. colorSaturation: null, // Can be 'none' if not necessary.
  43323. borderWidth: 0,
  43324. gapWidth: 0,
  43325. borderColor: '#fff',
  43326. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  43327. // border color is evaluated by color of current node and
  43328. // borderColorSaturation.
  43329. },
  43330. emphasis: {
  43331. upperLabel: {
  43332. show: true,
  43333. position: [0, '50%'],
  43334. color: '#fff',
  43335. ellipsis: true,
  43336. verticalAlign: 'middle'
  43337. }
  43338. },
  43339. visualDimension: 0, // Can be 0, 1, 2, 3.
  43340. visualMin: null,
  43341. visualMax: null,
  43342. color: [], // + treemapSeries.color should not be modified. Please only modified
  43343. // level[n].color (if necessary).
  43344. // + Specify color list of each level. level[0].color would be global
  43345. // color list if not specified. (see method `setDefault`).
  43346. // + But set as a empty array to forbid fetch color from global palette
  43347. // when using nodeModel.get('color'), otherwise nodes on deep level
  43348. // will always has color palette set and are not able to inherit color
  43349. // from parent node.
  43350. // + TreemapSeries.color can not be set as 'none', otherwise effect
  43351. // legend color fetching (see seriesColor.js).
  43352. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  43353. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  43354. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  43355. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  43356. // be rendered. Only works when sort is 'asc' or 'desc'.
  43357. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  43358. // grandchildren will not show.
  43359. // Why grandchildren? If not grandchildren but children,
  43360. // some siblings show children and some not,
  43361. // the appearance may be mess and not consistent,
  43362. levels: [] // Each item: {
  43363. // visibleMin, itemStyle, visualDimension, label
  43364. // }
  43365. // data: {
  43366. // value: [],
  43367. // children: [],
  43368. // link: 'http://xxx.xxx.xxx',
  43369. // target: 'blank' or 'self'
  43370. // }
  43371. },
  43372. /**
  43373. * @override
  43374. */
  43375. getInitialData: function (option, ecModel) {
  43376. // Create a virtual root.
  43377. var root = {name: option.name, children: option.data};
  43378. completeTreeValue(root);
  43379. var levels = option.levels || [];
  43380. levels = option.levels = setDefault(levels, ecModel);
  43381. var treeOption = {};
  43382. treeOption.levels = levels;
  43383. // Make sure always a new tree is created when setOption,
  43384. // in TreemapView, we check whether oldTree === newTree
  43385. // to choose mappings approach among old shapes and new shapes.
  43386. return Tree.createTree(root, this, treeOption).data;
  43387. },
  43388. optionUpdated: function () {
  43389. this.resetViewRoot();
  43390. },
  43391. /**
  43392. * @override
  43393. * @param {number} dataIndex
  43394. * @param {boolean} [mutipleSeries=false]
  43395. */
  43396. formatTooltip: function (dataIndex) {
  43397. var data = this.getData();
  43398. var value = this.getRawValue(dataIndex);
  43399. var formattedValue = isArray(value)
  43400. ? addCommas(value[0]) : addCommas(value);
  43401. var name = data.getName(dataIndex);
  43402. return encodeHTML(name + ': ' + formattedValue);
  43403. },
  43404. /**
  43405. * Add tree path to tooltip param
  43406. *
  43407. * @override
  43408. * @param {number} dataIndex
  43409. * @return {Object}
  43410. */
  43411. getDataParams: function (dataIndex) {
  43412. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  43413. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  43414. params.treePathInfo = wrapTreePathInfo(node, this);
  43415. return params;
  43416. },
  43417. /**
  43418. * @public
  43419. * @param {Object} layoutInfo {
  43420. * x: containerGroup x
  43421. * y: containerGroup y
  43422. * width: containerGroup width
  43423. * height: containerGroup height
  43424. * }
  43425. */
  43426. setLayoutInfo: function (layoutInfo) {
  43427. /**
  43428. * @readOnly
  43429. * @type {Object}
  43430. */
  43431. this.layoutInfo = this.layoutInfo || {};
  43432. extend(this.layoutInfo, layoutInfo);
  43433. },
  43434. /**
  43435. * @param {string} id
  43436. * @return {number} index
  43437. */
  43438. mapIdToIndex: function (id) {
  43439. // A feature is implemented:
  43440. // index is monotone increasing with the sequence of
  43441. // input id at the first time.
  43442. // This feature can make sure that each data item and its
  43443. // mapped color have the same index between data list and
  43444. // color list at the beginning, which is useful for user
  43445. // to adjust data-color mapping.
  43446. /**
  43447. * @private
  43448. * @type {Object}
  43449. */
  43450. var idIndexMap = this._idIndexMap;
  43451. if (!idIndexMap) {
  43452. idIndexMap = this._idIndexMap = createHashMap();
  43453. /**
  43454. * @private
  43455. * @type {number}
  43456. */
  43457. this._idIndexMapCount = 0;
  43458. }
  43459. var index = idIndexMap.get(id);
  43460. if (index == null) {
  43461. idIndexMap.set(id, index = this._idIndexMapCount++);
  43462. }
  43463. return index;
  43464. },
  43465. getViewRoot: function () {
  43466. return this._viewRoot;
  43467. },
  43468. /**
  43469. * @param {module:echarts/data/Tree~Node} [viewRoot]
  43470. */
  43471. resetViewRoot: function (viewRoot) {
  43472. viewRoot
  43473. ? (this._viewRoot = viewRoot)
  43474. : (viewRoot = this._viewRoot);
  43475. var root = this.getRawData().tree.root;
  43476. if (!viewRoot
  43477. || (viewRoot !== root && !root.contains(viewRoot))
  43478. ) {
  43479. this._viewRoot = root;
  43480. }
  43481. }
  43482. });
  43483. /**
  43484. * @param {Object} dataNode
  43485. */
  43486. function completeTreeValue(dataNode) {
  43487. // Postorder travel tree.
  43488. // If value of none-leaf node is not set,
  43489. // calculate it by suming up the value of all children.
  43490. var sum = 0;
  43491. each$1(dataNode.children, function (child) {
  43492. completeTreeValue(child);
  43493. var childValue = child.value;
  43494. isArray(childValue) && (childValue = childValue[0]);
  43495. sum += childValue;
  43496. });
  43497. var thisValue = dataNode.value;
  43498. if (isArray(thisValue)) {
  43499. thisValue = thisValue[0];
  43500. }
  43501. if (thisValue == null || isNaN(thisValue)) {
  43502. thisValue = sum;
  43503. }
  43504. // Value should not less than 0.
  43505. if (thisValue < 0) {
  43506. thisValue = 0;
  43507. }
  43508. isArray(dataNode.value)
  43509. ? (dataNode.value[0] = thisValue)
  43510. : (dataNode.value = thisValue);
  43511. }
  43512. /**
  43513. * set default to level configuration
  43514. */
  43515. function setDefault(levels, ecModel) {
  43516. var globalColorList = ecModel.get('color');
  43517. if (!globalColorList) {
  43518. return;
  43519. }
  43520. levels = levels || [];
  43521. var hasColorDefine;
  43522. each$1(levels, function (levelDefine) {
  43523. var model = new Model(levelDefine);
  43524. var modelColor = model.get('color');
  43525. if (model.get('itemStyle.color')
  43526. || (modelColor && modelColor !== 'none')
  43527. ) {
  43528. hasColorDefine = true;
  43529. }
  43530. });
  43531. if (!hasColorDefine) {
  43532. var level0 = levels[0] || (levels[0] = {});
  43533. level0.color = globalColorList.slice();
  43534. }
  43535. return levels;
  43536. }
  43537. /*
  43538. * Licensed to the Apache Software Foundation (ASF) under one
  43539. * or more contributor license agreements. See the NOTICE file
  43540. * distributed with this work for additional information
  43541. * regarding copyright ownership. The ASF licenses this file
  43542. * to you under the Apache License, Version 2.0 (the
  43543. * "License"); you may not use this file except in compliance
  43544. * with the License. You may obtain a copy of the License at
  43545. *
  43546. * http://www.apache.org/licenses/LICENSE-2.0
  43547. *
  43548. * Unless required by applicable law or agreed to in writing,
  43549. * software distributed under the License is distributed on an
  43550. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43551. * KIND, either express or implied. See the License for the
  43552. * specific language governing permissions and limitations
  43553. * under the License.
  43554. */
  43555. var TEXT_PADDING = 8;
  43556. var ITEM_GAP = 8;
  43557. var ARRAY_LENGTH = 5;
  43558. function Breadcrumb(containerGroup) {
  43559. /**
  43560. * @private
  43561. * @type {module:zrender/container/Group}
  43562. */
  43563. this.group = new Group();
  43564. containerGroup.add(this.group);
  43565. }
  43566. Breadcrumb.prototype = {
  43567. constructor: Breadcrumb,
  43568. render: function (seriesModel, api, targetNode, onSelect) {
  43569. var model = seriesModel.getModel('breadcrumb');
  43570. var thisGroup = this.group;
  43571. thisGroup.removeAll();
  43572. if (!model.get('show') || !targetNode) {
  43573. return;
  43574. }
  43575. var normalStyleModel = model.getModel('itemStyle');
  43576. // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  43577. var textStyleModel = normalStyleModel.getModel('textStyle');
  43578. var layoutParam = {
  43579. pos: {
  43580. left: model.get('left'),
  43581. right: model.get('right'),
  43582. top: model.get('top'),
  43583. bottom: model.get('bottom')
  43584. },
  43585. box: {
  43586. width: api.getWidth(),
  43587. height: api.getHeight()
  43588. },
  43589. emptyItemWidth: model.get('emptyItemWidth'),
  43590. totalWidth: 0,
  43591. renderList: []
  43592. };
  43593. this._prepare(targetNode, layoutParam, textStyleModel);
  43594. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  43595. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  43596. },
  43597. /**
  43598. * Prepare render list and total width
  43599. * @private
  43600. */
  43601. _prepare: function (targetNode, layoutParam, textStyleModel) {
  43602. for (var node = targetNode; node; node = node.parentNode) {
  43603. var text = node.getModel().get('name');
  43604. var textRect = textStyleModel.getTextRect(text);
  43605. var itemWidth = Math.max(
  43606. textRect.width + TEXT_PADDING * 2,
  43607. layoutParam.emptyItemWidth
  43608. );
  43609. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  43610. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  43611. }
  43612. },
  43613. /**
  43614. * @private
  43615. */
  43616. _renderContent: function (
  43617. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  43618. ) {
  43619. // Start rendering.
  43620. var lastX = 0;
  43621. var emptyItemWidth = layoutParam.emptyItemWidth;
  43622. var height = seriesModel.get('breadcrumb.height');
  43623. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  43624. var totalWidth = layoutParam.totalWidth;
  43625. var renderList = layoutParam.renderList;
  43626. for (var i = renderList.length - 1; i >= 0; i--) {
  43627. var item = renderList[i];
  43628. var itemNode = item.node;
  43629. var itemWidth = item.width;
  43630. var text = item.text;
  43631. // Hdie text and shorten width if necessary.
  43632. if (totalWidth > availableSize.width) {
  43633. totalWidth -= itemWidth - emptyItemWidth;
  43634. itemWidth = emptyItemWidth;
  43635. text = null;
  43636. }
  43637. var el = new Polygon({
  43638. shape: {
  43639. points: makeItemPoints(
  43640. lastX, 0, itemWidth, height,
  43641. i === renderList.length - 1, i === 0
  43642. )
  43643. },
  43644. style: defaults(
  43645. normalStyleModel.getItemStyle(),
  43646. {
  43647. lineJoin: 'bevel',
  43648. text: text,
  43649. textFill: textStyleModel.getTextColor(),
  43650. textFont: textStyleModel.getFont()
  43651. }
  43652. ),
  43653. z: 10,
  43654. onclick: curry(onSelect, itemNode)
  43655. });
  43656. this.group.add(el);
  43657. packEventData(el, seriesModel, itemNode);
  43658. lastX += itemWidth + ITEM_GAP;
  43659. }
  43660. },
  43661. /**
  43662. * @override
  43663. */
  43664. remove: function () {
  43665. this.group.removeAll();
  43666. }
  43667. };
  43668. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  43669. var points = [
  43670. [head ? x : x - ARRAY_LENGTH, y],
  43671. [x + itemWidth, y],
  43672. [x + itemWidth, y + itemHeight],
  43673. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  43674. ];
  43675. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  43676. !head && points.push([x, y + itemHeight / 2]);
  43677. return points;
  43678. }
  43679. // Package custom mouse event.
  43680. function packEventData(el, seriesModel, itemNode) {
  43681. el.eventData = {
  43682. componentType: 'series',
  43683. componentSubType: 'treemap',
  43684. componentIndex: seriesModel.componentIndex,
  43685. seriesIndex: seriesModel.componentIndex,
  43686. seriesName: seriesModel.name,
  43687. seriesType: 'treemap',
  43688. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  43689. nodeData: {
  43690. dataIndex: itemNode && itemNode.dataIndex,
  43691. name: itemNode && itemNode.name
  43692. },
  43693. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  43694. };
  43695. }
  43696. /*
  43697. * Licensed to the Apache Software Foundation (ASF) under one
  43698. * or more contributor license agreements. See the NOTICE file
  43699. * distributed with this work for additional information
  43700. * regarding copyright ownership. The ASF licenses this file
  43701. * to you under the Apache License, Version 2.0 (the
  43702. * "License"); you may not use this file except in compliance
  43703. * with the License. You may obtain a copy of the License at
  43704. *
  43705. * http://www.apache.org/licenses/LICENSE-2.0
  43706. *
  43707. * Unless required by applicable law or agreed to in writing,
  43708. * software distributed under the License is distributed on an
  43709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43710. * KIND, either express or implied. See the License for the
  43711. * specific language governing permissions and limitations
  43712. * under the License.
  43713. */
  43714. /**
  43715. * @param {number} [time=500] Time in ms
  43716. * @param {string} [easing='linear']
  43717. * @param {number} [delay=0]
  43718. * @param {Function} [callback]
  43719. *
  43720. * @example
  43721. * // Animate position
  43722. * animation
  43723. * .createWrap()
  43724. * .add(el1, {position: [10, 10]})
  43725. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  43726. * .done(function () { // done })
  43727. * .start('cubicOut');
  43728. */
  43729. function createWrap() {
  43730. var storage = [];
  43731. var elExistsMap = {};
  43732. var doneCallback;
  43733. return {
  43734. /**
  43735. * Caution: a el can only be added once, otherwise 'done'
  43736. * might not be called. This method checks this (by el.id),
  43737. * suppresses adding and returns false when existing el found.
  43738. *
  43739. * @param {modele:zrender/Element} el
  43740. * @param {Object} target
  43741. * @param {number} [time=500]
  43742. * @param {number} [delay=0]
  43743. * @param {string} [easing='linear']
  43744. * @return {boolean} Whether adding succeeded.
  43745. *
  43746. * @example
  43747. * add(el, target, time, delay, easing);
  43748. * add(el, target, time, easing);
  43749. * add(el, target, time);
  43750. * add(el, target);
  43751. */
  43752. add: function (el, target, time, delay, easing) {
  43753. if (isString(delay)) {
  43754. easing = delay;
  43755. delay = 0;
  43756. }
  43757. if (elExistsMap[el.id]) {
  43758. return false;
  43759. }
  43760. elExistsMap[el.id] = 1;
  43761. storage.push(
  43762. {el: el, target: target, time: time, delay: delay, easing: easing}
  43763. );
  43764. return true;
  43765. },
  43766. /**
  43767. * Only execute when animation finished. Will not execute when any
  43768. * of 'stop' or 'stopAnimation' called.
  43769. *
  43770. * @param {Function} callback
  43771. */
  43772. done: function (callback) {
  43773. doneCallback = callback;
  43774. return this;
  43775. },
  43776. /**
  43777. * Will stop exist animation firstly.
  43778. */
  43779. start: function () {
  43780. var count = storage.length;
  43781. for (var i = 0, len = storage.length; i < len; i++) {
  43782. var item = storage[i];
  43783. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  43784. }
  43785. return this;
  43786. function done() {
  43787. count--;
  43788. if (!count) {
  43789. storage.length = 0;
  43790. elExistsMap = {};
  43791. doneCallback && doneCallback();
  43792. }
  43793. }
  43794. }
  43795. };
  43796. }
  43797. /*
  43798. * Licensed to the Apache Software Foundation (ASF) under one
  43799. * or more contributor license agreements. See the NOTICE file
  43800. * distributed with this work for additional information
  43801. * regarding copyright ownership. The ASF licenses this file
  43802. * to you under the Apache License, Version 2.0 (the
  43803. * "License"); you may not use this file except in compliance
  43804. * with the License. You may obtain a copy of the License at
  43805. *
  43806. * http://www.apache.org/licenses/LICENSE-2.0
  43807. *
  43808. * Unless required by applicable law or agreed to in writing,
  43809. * software distributed under the License is distributed on an
  43810. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43811. * KIND, either express or implied. See the License for the
  43812. * specific language governing permissions and limitations
  43813. * under the License.
  43814. */
  43815. var bind$1 = bind;
  43816. var Group$2 = Group;
  43817. var Rect$1 = Rect;
  43818. var each$8 = each$1;
  43819. var DRAG_THRESHOLD = 3;
  43820. var PATH_LABEL_NOAMAL = ['label'];
  43821. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  43822. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  43823. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  43824. var Z_BASE = 10; // Should bigger than every z.
  43825. var Z_BG = 1;
  43826. var Z_CONTENT = 2;
  43827. var getItemStyleEmphasis = makeStyleMapper([
  43828. ['fill', 'color'],
  43829. // `borderColor` and `borderWidth` has been occupied,
  43830. // so use `stroke` to indicate the stroke of the rect.
  43831. ['stroke', 'strokeColor'],
  43832. ['lineWidth', 'strokeWidth'],
  43833. ['shadowBlur'],
  43834. ['shadowOffsetX'],
  43835. ['shadowOffsetY'],
  43836. ['shadowColor']
  43837. ]);
  43838. var getItemStyleNormal = function (model) {
  43839. // Normal style props should include emphasis style props.
  43840. var itemStyle = getItemStyleEmphasis(model);
  43841. // Clear styles set by emphasis.
  43842. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  43843. return itemStyle;
  43844. };
  43845. extendChartView({
  43846. type: 'treemap',
  43847. /**
  43848. * @override
  43849. */
  43850. init: function (o, api) {
  43851. /**
  43852. * @private
  43853. * @type {module:zrender/container/Group}
  43854. */
  43855. this._containerGroup;
  43856. /**
  43857. * @private
  43858. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  43859. */
  43860. this._storage = createStorage();
  43861. /**
  43862. * @private
  43863. * @type {module:echarts/data/Tree}
  43864. */
  43865. this._oldTree;
  43866. /**
  43867. * @private
  43868. * @type {module:echarts/chart/treemap/Breadcrumb}
  43869. */
  43870. this._breadcrumb;
  43871. /**
  43872. * @private
  43873. * @type {module:echarts/component/helper/RoamController}
  43874. */
  43875. this._controller;
  43876. /**
  43877. * 'ready', 'animating'
  43878. * @private
  43879. */
  43880. this._state = 'ready';
  43881. },
  43882. /**
  43883. * @override
  43884. */
  43885. render: function (seriesModel, ecModel, api, payload) {
  43886. var models = ecModel.findComponents({
  43887. mainType: 'series', subType: 'treemap', query: payload
  43888. });
  43889. if (indexOf(models, seriesModel) < 0) {
  43890. return;
  43891. }
  43892. this.seriesModel = seriesModel;
  43893. this.api = api;
  43894. this.ecModel = ecModel;
  43895. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  43896. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  43897. var payloadType = payload && payload.type;
  43898. var layoutInfo = seriesModel.layoutInfo;
  43899. var isInit = !this._oldTree;
  43900. var thisStorage = this._storage;
  43901. // Mark new root when action is treemapRootToNode.
  43902. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  43903. ? {
  43904. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  43905. direction: payload.direction
  43906. }
  43907. : null;
  43908. var containerGroup = this._giveContainerGroup(layoutInfo);
  43909. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  43910. (
  43911. !isInit && (
  43912. !payloadType
  43913. || payloadType === 'treemapZoomToNode'
  43914. || payloadType === 'treemapRootToNode'
  43915. )
  43916. )
  43917. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  43918. : renderResult.renderFinally();
  43919. this._resetController(api);
  43920. this._renderBreadcrumb(seriesModel, api, targetInfo);
  43921. },
  43922. /**
  43923. * @private
  43924. */
  43925. _giveContainerGroup: function (layoutInfo) {
  43926. var containerGroup = this._containerGroup;
  43927. if (!containerGroup) {
  43928. // FIXME
  43929. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  43930. containerGroup = this._containerGroup = new Group$2();
  43931. this._initEvents(containerGroup);
  43932. this.group.add(containerGroup);
  43933. }
  43934. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  43935. return containerGroup;
  43936. },
  43937. /**
  43938. * @private
  43939. */
  43940. _doRender: function (containerGroup, seriesModel, reRoot) {
  43941. var thisTree = seriesModel.getData().tree;
  43942. var oldTree = this._oldTree;
  43943. // Clear last shape records.
  43944. var lastsForAnimation = createStorage();
  43945. var thisStorage = createStorage();
  43946. var oldStorage = this._storage;
  43947. var willInvisibleEls = [];
  43948. var doRenderNode = curry(
  43949. renderNode, seriesModel,
  43950. thisStorage, oldStorage, reRoot,
  43951. lastsForAnimation, willInvisibleEls
  43952. );
  43953. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  43954. // the oldTree is actually losted, so we can not find all of the old graphic
  43955. // elements from tree. So we use this stragegy: make element storage, move
  43956. // from old storage to new storage, clear old storage.
  43957. dualTravel(
  43958. thisTree.root ? [thisTree.root] : [],
  43959. (oldTree && oldTree.root) ? [oldTree.root] : [],
  43960. containerGroup,
  43961. thisTree === oldTree || !oldTree,
  43962. 0
  43963. );
  43964. // Process all removing.
  43965. var willDeleteEls = clearStorage(oldStorage);
  43966. this._oldTree = thisTree;
  43967. this._storage = thisStorage;
  43968. return {
  43969. lastsForAnimation: lastsForAnimation,
  43970. willDeleteEls: willDeleteEls,
  43971. renderFinally: renderFinally
  43972. };
  43973. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  43974. // When 'render' is triggered by action,
  43975. // 'this' and 'old' may be the same tree,
  43976. // we use rawIndex in that case.
  43977. if (sameTree) {
  43978. oldViewChildren = thisViewChildren;
  43979. each$8(thisViewChildren, function (child, index) {
  43980. !child.isRemoved() && processNode(index, index);
  43981. });
  43982. }
  43983. // Diff hierarchically (diff only in each subtree, but not whole).
  43984. // because, consistency of view is important.
  43985. else {
  43986. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  43987. .add(processNode)
  43988. .update(processNode)
  43989. .remove(curry(processNode, null))
  43990. .execute();
  43991. }
  43992. function getKey(node) {
  43993. // Identify by name or raw index.
  43994. return node.getId();
  43995. }
  43996. function processNode(newIndex, oldIndex) {
  43997. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  43998. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  43999. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  44000. group && dualTravel(
  44001. thisNode && thisNode.viewChildren || [],
  44002. oldNode && oldNode.viewChildren || [],
  44003. group,
  44004. sameTree,
  44005. depth + 1
  44006. );
  44007. }
  44008. }
  44009. function clearStorage(storage) {
  44010. var willDeleteEls = createStorage();
  44011. storage && each$8(storage, function (store, storageName) {
  44012. var delEls = willDeleteEls[storageName];
  44013. each$8(store, function (el) {
  44014. el && (delEls.push(el), el.__tmWillDelete = 1);
  44015. });
  44016. });
  44017. return willDeleteEls;
  44018. }
  44019. function renderFinally() {
  44020. each$8(willDeleteEls, function (els) {
  44021. each$8(els, function (el) {
  44022. el.parent && el.parent.remove(el);
  44023. });
  44024. });
  44025. each$8(willInvisibleEls, function (el) {
  44026. el.invisible = true;
  44027. // Setting invisible is for optimizing, so no need to set dirty,
  44028. // just mark as invisible.
  44029. el.dirty();
  44030. });
  44031. }
  44032. },
  44033. /**
  44034. * @private
  44035. */
  44036. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  44037. if (!seriesModel.get('animation')) {
  44038. return;
  44039. }
  44040. var duration = seriesModel.get('animationDurationUpdate');
  44041. var easing = seriesModel.get('animationEasing');
  44042. var animationWrap = createWrap();
  44043. // Make delete animations.
  44044. each$8(renderResult.willDeleteEls, function (store, storageName) {
  44045. each$8(store, function (el, rawIndex) {
  44046. if (el.invisible) {
  44047. return;
  44048. }
  44049. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  44050. var target;
  44051. if (reRoot && reRoot.direction === 'drillDown') {
  44052. target = parent === reRoot.rootNodeGroup
  44053. // This is the content element of view root.
  44054. // Only `content` will enter this branch, because
  44055. // `background` and `nodeGroup` will not be deleted.
  44056. ? {
  44057. shape: {
  44058. x: 0,
  44059. y: 0,
  44060. width: parent.__tmNodeWidth,
  44061. height: parent.__tmNodeHeight
  44062. },
  44063. style: {
  44064. opacity: 0
  44065. }
  44066. }
  44067. // Others.
  44068. : {style: {opacity: 0}};
  44069. }
  44070. else {
  44071. var targetX = 0;
  44072. var targetY = 0;
  44073. if (!parent.__tmWillDelete) {
  44074. // Let node animate to right-bottom corner, cooperating with fadeout,
  44075. // which is appropriate for user understanding.
  44076. // Divided by 2 for reRoot rolling up effect.
  44077. targetX = parent.__tmNodeWidth / 2;
  44078. targetY = parent.__tmNodeHeight / 2;
  44079. }
  44080. target = storageName === 'nodeGroup'
  44081. ? {position: [targetX, targetY], style: {opacity: 0}}
  44082. : {
  44083. shape: {x: targetX, y: targetY, width: 0, height: 0},
  44084. style: {opacity: 0}
  44085. };
  44086. }
  44087. target && animationWrap.add(el, target, duration, easing);
  44088. });
  44089. });
  44090. // Make other animations
  44091. each$8(this._storage, function (store, storageName) {
  44092. each$8(store, function (el, rawIndex) {
  44093. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  44094. var target = {};
  44095. if (!last) {
  44096. return;
  44097. }
  44098. if (storageName === 'nodeGroup') {
  44099. if (last.old) {
  44100. target.position = el.position.slice();
  44101. el.attr('position', last.old);
  44102. }
  44103. }
  44104. else {
  44105. if (last.old) {
  44106. target.shape = extend({}, el.shape);
  44107. el.setShape(last.old);
  44108. }
  44109. if (last.fadein) {
  44110. el.setStyle('opacity', 0);
  44111. target.style = {opacity: 1};
  44112. }
  44113. // When animation is stopped for succedent animation starting,
  44114. // el.style.opacity might not be 1
  44115. else if (el.style.opacity !== 1) {
  44116. target.style = {opacity: 1};
  44117. }
  44118. }
  44119. animationWrap.add(el, target, duration, easing);
  44120. });
  44121. }, this);
  44122. this._state = 'animating';
  44123. animationWrap
  44124. .done(bind$1(function () {
  44125. this._state = 'ready';
  44126. renderResult.renderFinally();
  44127. }, this))
  44128. .start();
  44129. },
  44130. /**
  44131. * @private
  44132. */
  44133. _resetController: function (api) {
  44134. var controller = this._controller;
  44135. // Init controller.
  44136. if (!controller) {
  44137. controller = this._controller = new RoamController(api.getZr());
  44138. controller.enable(this.seriesModel.get('roam'));
  44139. controller.on('pan', bind$1(this._onPan, this));
  44140. controller.on('zoom', bind$1(this._onZoom, this));
  44141. }
  44142. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  44143. controller.setPointerChecker(function (e, x, y) {
  44144. return rect.contain(x, y);
  44145. });
  44146. },
  44147. /**
  44148. * @private
  44149. */
  44150. _clearController: function () {
  44151. var controller = this._controller;
  44152. if (controller) {
  44153. controller.dispose();
  44154. controller = null;
  44155. }
  44156. },
  44157. /**
  44158. * @private
  44159. */
  44160. _onPan: function (e) {
  44161. if (this._state !== 'animating'
  44162. && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD)
  44163. ) {
  44164. // These param must not be cached.
  44165. var root = this.seriesModel.getData().tree.root;
  44166. if (!root) {
  44167. return;
  44168. }
  44169. var rootLayout = root.getLayout();
  44170. if (!rootLayout) {
  44171. return;
  44172. }
  44173. this.api.dispatchAction({
  44174. type: 'treemapMove',
  44175. from: this.uid,
  44176. seriesId: this.seriesModel.id,
  44177. rootRect: {
  44178. x: rootLayout.x + e.dx, y: rootLayout.y + e.dy,
  44179. width: rootLayout.width, height: rootLayout.height
  44180. }
  44181. });
  44182. }
  44183. },
  44184. /**
  44185. * @private
  44186. */
  44187. _onZoom: function (e) {
  44188. var mouseX = e.originX;
  44189. var mouseY = e.originY;
  44190. if (this._state !== 'animating') {
  44191. // These param must not be cached.
  44192. var root = this.seriesModel.getData().tree.root;
  44193. if (!root) {
  44194. return;
  44195. }
  44196. var rootLayout = root.getLayout();
  44197. if (!rootLayout) {
  44198. return;
  44199. }
  44200. var rect = new BoundingRect(
  44201. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  44202. );
  44203. var layoutInfo = this.seriesModel.layoutInfo;
  44204. // Transform mouse coord from global to containerGroup.
  44205. mouseX -= layoutInfo.x;
  44206. mouseY -= layoutInfo.y;
  44207. // Scale root bounding rect.
  44208. var m = create$1();
  44209. translate(m, m, [-mouseX, -mouseY]);
  44210. scale$1(m, m, [e.scale, e.scale]);
  44211. translate(m, m, [mouseX, mouseY]);
  44212. rect.applyTransform(m);
  44213. this.api.dispatchAction({
  44214. type: 'treemapRender',
  44215. from: this.uid,
  44216. seriesId: this.seriesModel.id,
  44217. rootRect: {
  44218. x: rect.x, y: rect.y,
  44219. width: rect.width, height: rect.height
  44220. }
  44221. });
  44222. }
  44223. },
  44224. /**
  44225. * @private
  44226. */
  44227. _initEvents: function (containerGroup) {
  44228. containerGroup.on('click', function (e) {
  44229. if (this._state !== 'ready') {
  44230. return;
  44231. }
  44232. var nodeClick = this.seriesModel.get('nodeClick', true);
  44233. if (!nodeClick) {
  44234. return;
  44235. }
  44236. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  44237. if (!targetInfo) {
  44238. return;
  44239. }
  44240. var node = targetInfo.node;
  44241. if (node.getLayout().isLeafRoot) {
  44242. this._rootToNode(targetInfo);
  44243. }
  44244. else {
  44245. if (nodeClick === 'zoomToNode') {
  44246. this._zoomToNode(targetInfo);
  44247. }
  44248. else if (nodeClick === 'link') {
  44249. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  44250. var link = itemModel.get('link', true);
  44251. var linkTarget = itemModel.get('target', true) || 'blank';
  44252. link && window.open(link, linkTarget);
  44253. }
  44254. }
  44255. }, this);
  44256. },
  44257. /**
  44258. * @private
  44259. */
  44260. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  44261. if (!targetInfo) {
  44262. targetInfo = seriesModel.get('leafDepth', true) != null
  44263. ? {node: seriesModel.getViewRoot()}
  44264. // FIXME
  44265. // better way?
  44266. // Find breadcrumb tail on center of containerGroup.
  44267. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  44268. if (!targetInfo) {
  44269. targetInfo = {node: seriesModel.getData().tree.root};
  44270. }
  44271. }
  44272. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  44273. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  44274. function onSelect(node) {
  44275. if (this._state !== 'animating') {
  44276. aboveViewRoot(seriesModel.getViewRoot(), node)
  44277. ? this._rootToNode({node: node})
  44278. : this._zoomToNode({node: node});
  44279. }
  44280. }
  44281. },
  44282. /**
  44283. * @override
  44284. */
  44285. remove: function () {
  44286. this._clearController();
  44287. this._containerGroup && this._containerGroup.removeAll();
  44288. this._storage = createStorage();
  44289. this._state = 'ready';
  44290. this._breadcrumb && this._breadcrumb.remove();
  44291. },
  44292. dispose: function () {
  44293. this._clearController();
  44294. },
  44295. /**
  44296. * @private
  44297. */
  44298. _zoomToNode: function (targetInfo) {
  44299. this.api.dispatchAction({
  44300. type: 'treemapZoomToNode',
  44301. from: this.uid,
  44302. seriesId: this.seriesModel.id,
  44303. targetNode: targetInfo.node
  44304. });
  44305. },
  44306. /**
  44307. * @private
  44308. */
  44309. _rootToNode: function (targetInfo) {
  44310. this.api.dispatchAction({
  44311. type: 'treemapRootToNode',
  44312. from: this.uid,
  44313. seriesId: this.seriesModel.id,
  44314. targetNode: targetInfo.node
  44315. });
  44316. },
  44317. /**
  44318. * @public
  44319. * @param {number} x Global coord x.
  44320. * @param {number} y Global coord y.
  44321. * @return {Object} info If not found, return undefined;
  44322. * @return {number} info.node Target node.
  44323. * @return {number} info.offsetX x refer to target node.
  44324. * @return {number} info.offsetY y refer to target node.
  44325. */
  44326. findTarget: function (x, y) {
  44327. var targetInfo;
  44328. var viewRoot = this.seriesModel.getViewRoot();
  44329. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  44330. var bgEl = this._storage.background[node.getRawIndex()];
  44331. // If invisible, there might be no element.
  44332. if (bgEl) {
  44333. var point = bgEl.transformCoordToLocal(x, y);
  44334. var shape = bgEl.shape;
  44335. // For performance consideration, dont use 'getBoundingRect'.
  44336. if (shape.x <= point[0]
  44337. && point[0] <= shape.x + shape.width
  44338. && shape.y <= point[1]
  44339. && point[1] <= shape.y + shape.height
  44340. ) {
  44341. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  44342. }
  44343. else {
  44344. return false; // Suppress visit subtree.
  44345. }
  44346. }
  44347. }, this);
  44348. return targetInfo;
  44349. }
  44350. });
  44351. /**
  44352. * @inner
  44353. */
  44354. function createStorage() {
  44355. return {nodeGroup: [], background: [], content: []};
  44356. }
  44357. /**
  44358. * @inner
  44359. * @return Return undefined means do not travel further.
  44360. */
  44361. function renderNode(
  44362. seriesModel, thisStorage, oldStorage, reRoot,
  44363. lastsForAnimation, willInvisibleEls,
  44364. thisNode, oldNode, parentGroup, depth
  44365. ) {
  44366. // Whether under viewRoot.
  44367. if (!thisNode) {
  44368. // Deleting nodes will be performed finally. This method just find
  44369. // element from old storage, or create new element, set them to new
  44370. // storage, and set styles.
  44371. return;
  44372. }
  44373. // -------------------------------------------------------------------
  44374. // Start of closure variables available in "Procedures in renderNode".
  44375. var thisLayout = thisNode.getLayout();
  44376. if (!thisLayout || !thisLayout.isInView) {
  44377. return;
  44378. }
  44379. var thisWidth = thisLayout.width;
  44380. var thisHeight = thisLayout.height;
  44381. var borderWidth = thisLayout.borderWidth;
  44382. var thisInvisible = thisLayout.invisible;
  44383. var thisRawIndex = thisNode.getRawIndex();
  44384. var oldRawIndex = oldNode && oldNode.getRawIndex();
  44385. var thisViewChildren = thisNode.viewChildren;
  44386. var upperHeight = thisLayout.upperHeight;
  44387. var isParent = thisViewChildren && thisViewChildren.length;
  44388. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  44389. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle');
  44390. // End of closure ariables available in "Procedures in renderNode".
  44391. // -----------------------------------------------------------------
  44392. // Node group
  44393. var group = giveGraphic('nodeGroup', Group$2);
  44394. if (!group) {
  44395. return;
  44396. }
  44397. parentGroup.add(group);
  44398. // x,y are not set when el is above view root.
  44399. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  44400. group.__tmNodeWidth = thisWidth;
  44401. group.__tmNodeHeight = thisHeight;
  44402. if (thisLayout.isAboveViewRoot) {
  44403. return group;
  44404. }
  44405. // Background
  44406. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  44407. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  44408. // No children, render content.
  44409. if (!isParent) {
  44410. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  44411. content && renderContent(group, content);
  44412. }
  44413. return group;
  44414. // ----------------------------
  44415. // | Procedures in renderNode |
  44416. // ----------------------------
  44417. function renderBackground(group, bg, useUpperLabel) {
  44418. // For tooltip.
  44419. bg.dataIndex = thisNode.dataIndex;
  44420. bg.seriesIndex = seriesModel.seriesIndex;
  44421. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  44422. var visualBorderColor = thisNode.getVisual('borderColor', true);
  44423. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  44424. updateStyle(bg, function () {
  44425. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  44426. normalStyle.fill = visualBorderColor;
  44427. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  44428. emphasisStyle.fill = emphasisBorderColor;
  44429. if (useUpperLabel) {
  44430. var upperLabelWidth = thisWidth - 2 * borderWidth;
  44431. prepareText(
  44432. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  44433. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  44434. );
  44435. }
  44436. // For old bg.
  44437. else {
  44438. normalStyle.text = emphasisStyle.text = null;
  44439. }
  44440. bg.setStyle(normalStyle);
  44441. setHoverStyle(bg, emphasisStyle);
  44442. });
  44443. group.add(bg);
  44444. }
  44445. function renderContent(group, content) {
  44446. // For tooltip.
  44447. content.dataIndex = thisNode.dataIndex;
  44448. content.seriesIndex = seriesModel.seriesIndex;
  44449. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  44450. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  44451. content.culling = true;
  44452. content.setShape({
  44453. x: borderWidth,
  44454. y: borderWidth,
  44455. width: contentWidth,
  44456. height: contentHeight
  44457. });
  44458. var visualColor = thisNode.getVisual('color', true);
  44459. updateStyle(content, function () {
  44460. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  44461. normalStyle.fill = visualColor;
  44462. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  44463. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  44464. content.setStyle(normalStyle);
  44465. setHoverStyle(content, emphasisStyle);
  44466. });
  44467. group.add(content);
  44468. }
  44469. function updateStyle(element, cb) {
  44470. if (!thisInvisible) {
  44471. // If invisible, do not set visual, otherwise the element will
  44472. // change immediately before animation. We think it is OK to
  44473. // remain its origin color when moving out of the view window.
  44474. cb();
  44475. if (!element.__tmWillVisible) {
  44476. element.invisible = false;
  44477. }
  44478. }
  44479. else {
  44480. // Delay invisible setting utill animation finished,
  44481. // avoid element vanish suddenly before animation.
  44482. !element.invisible && willInvisibleEls.push(element);
  44483. }
  44484. }
  44485. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  44486. var nodeModel = thisNode.getModel();
  44487. var text = retrieve(
  44488. seriesModel.getFormattedLabel(
  44489. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  44490. ),
  44491. nodeModel.get('name')
  44492. );
  44493. if (!upperLabelRect && thisLayout.isLeafRoot) {
  44494. var iconChar = seriesModel.get('drillDownIcon', true);
  44495. text = iconChar ? iconChar + ' ' + text : text;
  44496. }
  44497. var normalLabelModel = nodeModel.getModel(
  44498. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  44499. );
  44500. var emphasisLabelModel = nodeModel.getModel(
  44501. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  44502. );
  44503. var isShow = normalLabelModel.getShallow('show');
  44504. setLabelStyle(
  44505. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  44506. {
  44507. defaultText: isShow ? text : null,
  44508. autoColor: visualColor,
  44509. isRectText: true
  44510. }
  44511. );
  44512. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  44513. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  44514. ? {
  44515. outerWidth: width,
  44516. outerHeight: height,
  44517. minChar: 2
  44518. }
  44519. : null;
  44520. }
  44521. function giveGraphic(storageName, Ctor, depth, z) {
  44522. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  44523. var lasts = lastsForAnimation[storageName];
  44524. if (element) {
  44525. // Remove from oldStorage
  44526. oldStorage[storageName][oldRawIndex] = null;
  44527. prepareAnimationWhenHasOld(lasts, element, storageName);
  44528. }
  44529. // If invisible and no old element, do not create new element (for optimizing).
  44530. else if (!thisInvisible) {
  44531. element = new Ctor({z: calculateZ(depth, z)});
  44532. element.__tmDepth = depth;
  44533. element.__tmStorageName = storageName;
  44534. prepareAnimationWhenNoOld(lasts, element, storageName);
  44535. }
  44536. // Set to thisStorage
  44537. return (thisStorage[storageName][thisRawIndex] = element);
  44538. }
  44539. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  44540. var lastCfg = lasts[thisRawIndex] = {};
  44541. lastCfg.old = storageName === 'nodeGroup'
  44542. ? element.position.slice()
  44543. : extend({}, element.shape);
  44544. }
  44545. // If a element is new, we need to find the animation start point carefully,
  44546. // otherwise it will looks strange when 'zoomToNode'.
  44547. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  44548. var lastCfg = lasts[thisRawIndex] = {};
  44549. var parentNode = thisNode.parentNode;
  44550. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  44551. var parentOldX = 0;
  44552. var parentOldY = 0;
  44553. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  44554. // For convenience, get old bounding rect from background.
  44555. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  44556. if (!reRoot && parentOldBg && parentOldBg.old) {
  44557. parentOldX = parentOldBg.old.width;
  44558. parentOldY = parentOldBg.old.height;
  44559. }
  44560. // When no parent old shape found, its parent is new too,
  44561. // so we can just use {x:0, y:0}.
  44562. lastCfg.old = storageName === 'nodeGroup'
  44563. ? [0, parentOldY]
  44564. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  44565. }
  44566. // Fade in, user can be aware that these nodes are new.
  44567. lastCfg.fadein = storageName !== 'nodeGroup';
  44568. }
  44569. }
  44570. // We can not set all backgroud with the same z, Because the behaviour of
  44571. // drill down and roll up differ background creation sequence from tree
  44572. // hierarchy sequence, which cause that lowser background element overlap
  44573. // upper ones. So we calculate z based on depth.
  44574. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  44575. // treemap with large z overlaps other components.
  44576. function calculateZ(depth, zInLevel) {
  44577. var zb = depth * Z_BASE + zInLevel;
  44578. return (zb - 1) / zb;
  44579. }
  44580. /*
  44581. * Licensed to the Apache Software Foundation (ASF) under one
  44582. * or more contributor license agreements. See the NOTICE file
  44583. * distributed with this work for additional information
  44584. * regarding copyright ownership. The ASF licenses this file
  44585. * to you under the Apache License, Version 2.0 (the
  44586. * "License"); you may not use this file except in compliance
  44587. * with the License. You may obtain a copy of the License at
  44588. *
  44589. * http://www.apache.org/licenses/LICENSE-2.0
  44590. *
  44591. * Unless required by applicable law or agreed to in writing,
  44592. * software distributed under the License is distributed on an
  44593. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44594. * KIND, either express or implied. See the License for the
  44595. * specific language governing permissions and limitations
  44596. * under the License.
  44597. */
  44598. /**
  44599. * @file Treemap action
  44600. */
  44601. var noop$1 = function () {};
  44602. var actionTypes = [
  44603. 'treemapZoomToNode',
  44604. 'treemapRender',
  44605. 'treemapMove'
  44606. ];
  44607. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  44608. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  44609. }
  44610. registerAction(
  44611. {type: 'treemapRootToNode', update: 'updateView'},
  44612. function (payload, ecModel) {
  44613. ecModel.eachComponent(
  44614. {mainType: 'series', subType: 'treemap', query: payload},
  44615. handleRootToNode
  44616. );
  44617. function handleRootToNode(model, index) {
  44618. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  44619. var targetInfo = retrieveTargetInfo(payload, types, model);
  44620. if (targetInfo) {
  44621. var originViewRoot = model.getViewRoot();
  44622. if (originViewRoot) {
  44623. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  44624. ? 'rollUp' : 'drillDown';
  44625. }
  44626. model.resetViewRoot(targetInfo.node);
  44627. }
  44628. }
  44629. }
  44630. );
  44631. /*
  44632. * Licensed to the Apache Software Foundation (ASF) under one
  44633. * or more contributor license agreements. See the NOTICE file
  44634. * distributed with this work for additional information
  44635. * regarding copyright ownership. The ASF licenses this file
  44636. * to you under the Apache License, Version 2.0 (the
  44637. * "License"); you may not use this file except in compliance
  44638. * with the License. You may obtain a copy of the License at
  44639. *
  44640. * http://www.apache.org/licenses/LICENSE-2.0
  44641. *
  44642. * Unless required by applicable law or agreed to in writing,
  44643. * software distributed under the License is distributed on an
  44644. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44645. * KIND, either express or implied. See the License for the
  44646. * specific language governing permissions and limitations
  44647. * under the License.
  44648. */
  44649. var each$9 = each$1;
  44650. var isObject$5 = isObject$1;
  44651. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  44652. /**
  44653. * @param {Object} option
  44654. * @param {string} [option.type] See visualHandlers.
  44655. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  44656. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  44657. * required when mappingMethod is 'linear'
  44658. * @param {Array.<Object>=} [option.pieceList] [
  44659. * {value: someValue},
  44660. * {interval: [min1, max1], visual: {...}},
  44661. * {interval: [min2, max2]}
  44662. * ],
  44663. * required when mappingMethod is 'piecewise'.
  44664. * Visual for only each piece can be specified.
  44665. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  44666. * required when mappingMethod is 'category'.
  44667. * If no option.categories, categories is set
  44668. * as [0, 1, 2, ...].
  44669. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  44670. * @param {(Array|Object|*)} [option.visual] Visual data.
  44671. * when mappingMethod is 'category',
  44672. * visual data can be array or object
  44673. * (like: {cate1: '#222', none: '#fff'})
  44674. * or primary types (which represents
  44675. * defualt category visual), otherwise visual
  44676. * can be array or primary (which will be
  44677. * normalized to array).
  44678. *
  44679. */
  44680. var VisualMapping = function (option) {
  44681. var mappingMethod = option.mappingMethod;
  44682. var visualType = option.type;
  44683. /**
  44684. * @readOnly
  44685. * @type {Object}
  44686. */
  44687. var thisOption = this.option = clone(option);
  44688. /**
  44689. * @readOnly
  44690. * @type {string}
  44691. */
  44692. this.type = visualType;
  44693. /**
  44694. * @readOnly
  44695. * @type {string}
  44696. */
  44697. this.mappingMethod = mappingMethod;
  44698. /**
  44699. * @private
  44700. * @type {Function}
  44701. */
  44702. this._normalizeData = normalizers[mappingMethod];
  44703. var visualHandler = visualHandlers[visualType];
  44704. /**
  44705. * @public
  44706. * @type {Function}
  44707. */
  44708. this.applyVisual = visualHandler.applyVisual;
  44709. /**
  44710. * @public
  44711. * @type {Function}
  44712. */
  44713. this.getColorMapper = visualHandler.getColorMapper;
  44714. /**
  44715. * @private
  44716. * @type {Function}
  44717. */
  44718. this._doMap = visualHandler._doMap[mappingMethod];
  44719. if (mappingMethod === 'piecewise') {
  44720. normalizeVisualRange(thisOption);
  44721. preprocessForPiecewise(thisOption);
  44722. }
  44723. else if (mappingMethod === 'category') {
  44724. thisOption.categories
  44725. ? preprocessForSpecifiedCategory(thisOption)
  44726. // categories is ordinal when thisOption.categories not specified,
  44727. // which need no more preprocess except normalize visual.
  44728. : normalizeVisualRange(thisOption, true);
  44729. }
  44730. else { // mappingMethod === 'linear' or 'fixed'
  44731. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  44732. normalizeVisualRange(thisOption);
  44733. }
  44734. };
  44735. VisualMapping.prototype = {
  44736. constructor: VisualMapping,
  44737. mapValueToVisual: function (value) {
  44738. var normalized = this._normalizeData(value);
  44739. return this._doMap(normalized, value);
  44740. },
  44741. getNormalizer: function () {
  44742. return bind(this._normalizeData, this);
  44743. }
  44744. };
  44745. var visualHandlers = VisualMapping.visualHandlers = {
  44746. color: {
  44747. applyVisual: makeApplyVisual('color'),
  44748. /**
  44749. * Create a mapper function
  44750. * @return {Function}
  44751. */
  44752. getColorMapper: function () {
  44753. var thisOption = this.option;
  44754. return bind(
  44755. thisOption.mappingMethod === 'category'
  44756. ? function (value, isNormalized) {
  44757. !isNormalized && (value = this._normalizeData(value));
  44758. return doMapCategory.call(this, value);
  44759. }
  44760. : function (value, isNormalized, out) {
  44761. // If output rgb array
  44762. // which will be much faster and useful in pixel manipulation
  44763. var returnRGBArray = !!out;
  44764. !isNormalized && (value = this._normalizeData(value));
  44765. out = fastLerp(value, thisOption.parsedVisual, out);
  44766. return returnRGBArray ? out : stringify(out, 'rgba');
  44767. },
  44768. this
  44769. );
  44770. },
  44771. _doMap: {
  44772. linear: function (normalized) {
  44773. return stringify(
  44774. fastLerp(normalized, this.option.parsedVisual),
  44775. 'rgba'
  44776. );
  44777. },
  44778. category: doMapCategory,
  44779. piecewise: function (normalized, value) {
  44780. var result = getSpecifiedVisual.call(this, value);
  44781. if (result == null) {
  44782. result = stringify(
  44783. fastLerp(normalized, this.option.parsedVisual),
  44784. 'rgba'
  44785. );
  44786. }
  44787. return result;
  44788. },
  44789. fixed: doMapFixed
  44790. }
  44791. },
  44792. colorHue: makePartialColorVisualHandler(function (color, value) {
  44793. return modifyHSL(color, value);
  44794. }),
  44795. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  44796. return modifyHSL(color, null, value);
  44797. }),
  44798. colorLightness: makePartialColorVisualHandler(function (color, value) {
  44799. return modifyHSL(color, null, null, value);
  44800. }),
  44801. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  44802. return modifyAlpha(color, value);
  44803. }),
  44804. opacity: {
  44805. applyVisual: makeApplyVisual('opacity'),
  44806. _doMap: makeDoMap([0, 1])
  44807. },
  44808. liftZ: {
  44809. applyVisual: makeApplyVisual('liftZ'),
  44810. _doMap: {
  44811. linear: doMapFixed,
  44812. category: doMapFixed,
  44813. piecewise: doMapFixed,
  44814. fixed: doMapFixed
  44815. }
  44816. },
  44817. symbol: {
  44818. applyVisual: function (value, getter, setter) {
  44819. var symbolCfg = this.mapValueToVisual(value);
  44820. if (isString(symbolCfg)) {
  44821. setter('symbol', symbolCfg);
  44822. }
  44823. else if (isObject$5(symbolCfg)) {
  44824. for (var name in symbolCfg) {
  44825. if (symbolCfg.hasOwnProperty(name)) {
  44826. setter(name, symbolCfg[name]);
  44827. }
  44828. }
  44829. }
  44830. },
  44831. _doMap: {
  44832. linear: doMapToArray,
  44833. category: doMapCategory,
  44834. piecewise: function (normalized, value) {
  44835. var result = getSpecifiedVisual.call(this, value);
  44836. if (result == null) {
  44837. result = doMapToArray.call(this, normalized);
  44838. }
  44839. return result;
  44840. },
  44841. fixed: doMapFixed
  44842. }
  44843. },
  44844. symbolSize: {
  44845. applyVisual: makeApplyVisual('symbolSize'),
  44846. _doMap: makeDoMap([0, 1])
  44847. }
  44848. };
  44849. function preprocessForPiecewise(thisOption) {
  44850. var pieceList = thisOption.pieceList;
  44851. thisOption.hasSpecialVisual = false;
  44852. each$1(pieceList, function (piece, index) {
  44853. piece.originIndex = index;
  44854. // piece.visual is "result visual value" but not
  44855. // a visual range, so it does not need to be normalized.
  44856. if (piece.visual != null) {
  44857. thisOption.hasSpecialVisual = true;
  44858. }
  44859. });
  44860. }
  44861. function preprocessForSpecifiedCategory(thisOption) {
  44862. // Hash categories.
  44863. var categories = thisOption.categories;
  44864. var visual = thisOption.visual;
  44865. var categoryMap = thisOption.categoryMap = {};
  44866. each$9(categories, function (cate, index) {
  44867. categoryMap[cate] = index;
  44868. });
  44869. // Process visual map input.
  44870. if (!isArray(visual)) {
  44871. var visualArr = [];
  44872. if (isObject$1(visual)) {
  44873. each$9(visual, function (v, cate) {
  44874. var index = categoryMap[cate];
  44875. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  44876. });
  44877. }
  44878. else { // Is primary type, represents default visual.
  44879. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  44880. }
  44881. visual = setVisualToOption(thisOption, visualArr);
  44882. }
  44883. // Remove categories that has no visual,
  44884. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  44885. for (var i = categories.length - 1; i >= 0; i--) {
  44886. if (visual[i] == null) {
  44887. delete categoryMap[categories[i]];
  44888. categories.pop();
  44889. }
  44890. }
  44891. }
  44892. function normalizeVisualRange(thisOption, isCategory) {
  44893. var visual = thisOption.visual;
  44894. var visualArr = [];
  44895. if (isObject$1(visual)) {
  44896. each$9(visual, function (v) {
  44897. visualArr.push(v);
  44898. });
  44899. }
  44900. else if (visual != null) {
  44901. visualArr.push(visual);
  44902. }
  44903. var doNotNeedPair = {color: 1, symbol: 1};
  44904. if (!isCategory
  44905. && visualArr.length === 1
  44906. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  44907. ) {
  44908. // Do not care visualArr.length === 0, which is illegal.
  44909. visualArr[1] = visualArr[0];
  44910. }
  44911. setVisualToOption(thisOption, visualArr);
  44912. }
  44913. function makePartialColorVisualHandler(applyValue) {
  44914. return {
  44915. applyVisual: function (value, getter, setter) {
  44916. value = this.mapValueToVisual(value);
  44917. // Must not be array value
  44918. setter('color', applyValue(getter('color'), value));
  44919. },
  44920. _doMap: makeDoMap([0, 1])
  44921. };
  44922. }
  44923. function doMapToArray(normalized) {
  44924. var visual = this.option.visual;
  44925. return visual[
  44926. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  44927. ] || {};
  44928. }
  44929. function makeApplyVisual(visualType) {
  44930. return function (value, getter, setter) {
  44931. setter(visualType, this.mapValueToVisual(value));
  44932. };
  44933. }
  44934. function doMapCategory(normalized) {
  44935. var visual = this.option.visual;
  44936. return visual[
  44937. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  44938. ? normalized % visual.length
  44939. : normalized
  44940. ];
  44941. }
  44942. function doMapFixed() {
  44943. return this.option.visual[0];
  44944. }
  44945. function makeDoMap(sourceExtent) {
  44946. return {
  44947. linear: function (normalized) {
  44948. return linearMap(normalized, sourceExtent, this.option.visual, true);
  44949. },
  44950. category: doMapCategory,
  44951. piecewise: function (normalized, value) {
  44952. var result = getSpecifiedVisual.call(this, value);
  44953. if (result == null) {
  44954. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  44955. }
  44956. return result;
  44957. },
  44958. fixed: doMapFixed
  44959. };
  44960. }
  44961. function getSpecifiedVisual(value) {
  44962. var thisOption = this.option;
  44963. var pieceList = thisOption.pieceList;
  44964. if (thisOption.hasSpecialVisual) {
  44965. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  44966. var piece = pieceList[pieceIndex];
  44967. if (piece && piece.visual) {
  44968. return piece.visual[this.type];
  44969. }
  44970. }
  44971. }
  44972. function setVisualToOption(thisOption, visualArr) {
  44973. thisOption.visual = visualArr;
  44974. if (thisOption.type === 'color') {
  44975. thisOption.parsedVisual = map(visualArr, function (item) {
  44976. return parse(item);
  44977. });
  44978. }
  44979. return visualArr;
  44980. }
  44981. /**
  44982. * Normalizers by mapping methods.
  44983. */
  44984. var normalizers = {
  44985. linear: function (value) {
  44986. return linearMap(value, this.option.dataExtent, [0, 1], true);
  44987. },
  44988. piecewise: function (value) {
  44989. var pieceList = this.option.pieceList;
  44990. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  44991. if (pieceIndex != null) {
  44992. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  44993. }
  44994. },
  44995. category: function (value) {
  44996. var index = this.option.categories
  44997. ? this.option.categoryMap[value]
  44998. : value; // ordinal
  44999. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  45000. },
  45001. fixed: noop
  45002. };
  45003. /**
  45004. * List available visual types.
  45005. *
  45006. * @public
  45007. * @return {Array.<string>}
  45008. */
  45009. VisualMapping.listVisualTypes = function () {
  45010. var visualTypes = [];
  45011. each$1(visualHandlers, function (handler, key) {
  45012. visualTypes.push(key);
  45013. });
  45014. return visualTypes;
  45015. };
  45016. /**
  45017. * @public
  45018. */
  45019. VisualMapping.addVisualHandler = function (name, handler) {
  45020. visualHandlers[name] = handler;
  45021. };
  45022. /**
  45023. * @public
  45024. */
  45025. VisualMapping.isValidType = function (visualType) {
  45026. return visualHandlers.hasOwnProperty(visualType);
  45027. };
  45028. /**
  45029. * Convinent method.
  45030. * Visual can be Object or Array or primary type.
  45031. *
  45032. * @public
  45033. */
  45034. VisualMapping.eachVisual = function (visual, callback, context) {
  45035. if (isObject$1(visual)) {
  45036. each$1(visual, callback, context);
  45037. }
  45038. else {
  45039. callback.call(context, visual);
  45040. }
  45041. };
  45042. VisualMapping.mapVisual = function (visual, callback, context) {
  45043. var isPrimary;
  45044. var newVisual = isArray(visual)
  45045. ? []
  45046. : isObject$1(visual)
  45047. ? {}
  45048. : (isPrimary = true, null);
  45049. VisualMapping.eachVisual(visual, function (v, key) {
  45050. var newVal = callback.call(context, v, key);
  45051. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  45052. });
  45053. return newVisual;
  45054. };
  45055. /**
  45056. * @public
  45057. * @param {Object} obj
  45058. * @return {Object} new object containers visual values.
  45059. * If no visuals, return null.
  45060. */
  45061. VisualMapping.retrieveVisuals = function (obj) {
  45062. var ret = {};
  45063. var hasVisual;
  45064. obj && each$9(visualHandlers, function (h, visualType) {
  45065. if (obj.hasOwnProperty(visualType)) {
  45066. ret[visualType] = obj[visualType];
  45067. hasVisual = true;
  45068. }
  45069. });
  45070. return hasVisual ? ret : null;
  45071. };
  45072. /**
  45073. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  45074. *
  45075. * @public
  45076. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  45077. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  45078. * @return {Array.<string>} Sorted visual types.
  45079. */
  45080. VisualMapping.prepareVisualTypes = function (visualTypes) {
  45081. if (isObject$5(visualTypes)) {
  45082. var types = [];
  45083. each$9(visualTypes, function (item, type) {
  45084. types.push(type);
  45085. });
  45086. visualTypes = types;
  45087. }
  45088. else if (isArray(visualTypes)) {
  45089. visualTypes = visualTypes.slice();
  45090. }
  45091. else {
  45092. return [];
  45093. }
  45094. visualTypes.sort(function (type1, type2) {
  45095. // color should be front of colorSaturation, colorAlpha, ...
  45096. // symbol and symbolSize do not matter.
  45097. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  45098. ? 1 : -1;
  45099. });
  45100. return visualTypes;
  45101. };
  45102. /**
  45103. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  45104. * Other visuals are only depends on themself.
  45105. *
  45106. * @public
  45107. * @param {string} visualType1
  45108. * @param {string} visualType2
  45109. * @return {boolean}
  45110. */
  45111. VisualMapping.dependsOn = function (visualType1, visualType2) {
  45112. return visualType2 === 'color'
  45113. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  45114. : visualType1 === visualType2;
  45115. };
  45116. /**
  45117. * @param {number} value
  45118. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  45119. * Always from small to big.
  45120. * @param {boolean} [findClosestWhenOutside=false]
  45121. * @return {number} index
  45122. */
  45123. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  45124. var possibleI;
  45125. var abs = Infinity;
  45126. // value has the higher priority.
  45127. for (var i = 0, len = pieceList.length; i < len; i++) {
  45128. var pieceValue = pieceList[i].value;
  45129. if (pieceValue != null) {
  45130. if (pieceValue === value
  45131. // FIXME
  45132. // It is supposed to compare value according to value type of dimension,
  45133. // but currently value type can exactly be string or number.
  45134. // Compromise for numeric-like string (like '12'), especially
  45135. // in the case that visualMap.categories is ['22', '33'].
  45136. || (typeof pieceValue === 'string' && pieceValue === value + '')
  45137. ) {
  45138. return i;
  45139. }
  45140. findClosestWhenOutside && updatePossible(pieceValue, i);
  45141. }
  45142. }
  45143. for (var i = 0, len = pieceList.length; i < len; i++) {
  45144. var piece = pieceList[i];
  45145. var interval = piece.interval;
  45146. var close = piece.close;
  45147. if (interval) {
  45148. if (interval[0] === -Infinity) {
  45149. if (littleThan(close[1], value, interval[1])) {
  45150. return i;
  45151. }
  45152. }
  45153. else if (interval[1] === Infinity) {
  45154. if (littleThan(close[0], interval[0], value)) {
  45155. return i;
  45156. }
  45157. }
  45158. else if (
  45159. littleThan(close[0], interval[0], value)
  45160. && littleThan(close[1], value, interval[1])
  45161. ) {
  45162. return i;
  45163. }
  45164. findClosestWhenOutside && updatePossible(interval[0], i);
  45165. findClosestWhenOutside && updatePossible(interval[1], i);
  45166. }
  45167. }
  45168. if (findClosestWhenOutside) {
  45169. return value === Infinity
  45170. ? pieceList.length - 1
  45171. : value === -Infinity
  45172. ? 0
  45173. : possibleI;
  45174. }
  45175. function updatePossible(val, index) {
  45176. var newAbs = Math.abs(val - value);
  45177. if (newAbs < abs) {
  45178. abs = newAbs;
  45179. possibleI = index;
  45180. }
  45181. }
  45182. };
  45183. function littleThan(close, a, b) {
  45184. return close ? a <= b : a < b;
  45185. }
  45186. /*
  45187. * Licensed to the Apache Software Foundation (ASF) under one
  45188. * or more contributor license agreements. See the NOTICE file
  45189. * distributed with this work for additional information
  45190. * regarding copyright ownership. The ASF licenses this file
  45191. * to you under the Apache License, Version 2.0 (the
  45192. * "License"); you may not use this file except in compliance
  45193. * with the License. You may obtain a copy of the License at
  45194. *
  45195. * http://www.apache.org/licenses/LICENSE-2.0
  45196. *
  45197. * Unless required by applicable law or agreed to in writing,
  45198. * software distributed under the License is distributed on an
  45199. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45200. * KIND, either express or implied. See the License for the
  45201. * specific language governing permissions and limitations
  45202. * under the License.
  45203. */
  45204. var isArray$2 = isArray;
  45205. var ITEM_STYLE_NORMAL = 'itemStyle';
  45206. var treemapVisual = {
  45207. seriesType: 'treemap',
  45208. reset: function (seriesModel, ecModel, api, payload) {
  45209. var tree = seriesModel.getData().tree;
  45210. var root = tree.root;
  45211. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  45212. if (root.isRemoved()) {
  45213. return;
  45214. }
  45215. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  45216. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  45217. });
  45218. travelTree(
  45219. root, // Visual should calculate from tree root but not view root.
  45220. {},
  45221. levelItemStyles,
  45222. seriesItemStyleModel,
  45223. seriesModel.getViewRoot().getAncestors(),
  45224. seriesModel
  45225. );
  45226. }
  45227. };
  45228. function travelTree(
  45229. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  45230. viewRootAncestors, seriesModel
  45231. ) {
  45232. var nodeModel = node.getModel();
  45233. var nodeLayout = node.getLayout();
  45234. // Optimize
  45235. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  45236. return;
  45237. }
  45238. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  45239. var levelItemStyle = levelItemStyles[node.depth];
  45240. var visuals = buildVisuals(
  45241. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  45242. );
  45243. // calculate border color
  45244. var borderColor = nodeItemStyleModel.get('borderColor');
  45245. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  45246. var thisNodeColor;
  45247. if (borderColorSaturation != null) {
  45248. // For performance, do not always execute 'calculateColor'.
  45249. thisNodeColor = calculateColor(visuals, node);
  45250. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  45251. }
  45252. node.setVisual('borderColor', borderColor);
  45253. var viewChildren = node.viewChildren;
  45254. if (!viewChildren || !viewChildren.length) {
  45255. thisNodeColor = calculateColor(visuals, node);
  45256. // Apply visual to this node.
  45257. node.setVisual('color', thisNodeColor);
  45258. }
  45259. else {
  45260. var mapping = buildVisualMapping(
  45261. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  45262. );
  45263. // Designate visual to children.
  45264. each$1(viewChildren, function (child, index) {
  45265. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  45266. if (child.depth >= viewRootAncestors.length
  45267. || child === viewRootAncestors[child.depth]
  45268. ) {
  45269. var childVisual = mapVisual$1(
  45270. nodeModel, visuals, child, index, mapping, seriesModel
  45271. );
  45272. travelTree(
  45273. child, childVisual, levelItemStyles, seriesItemStyleModel,
  45274. viewRootAncestors, seriesModel
  45275. );
  45276. }
  45277. });
  45278. }
  45279. }
  45280. function buildVisuals(
  45281. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  45282. ) {
  45283. var visuals = extend({}, designatedVisual);
  45284. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  45285. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  45286. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  45287. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  45288. val == null && (val = designatedVisual[visualName]);
  45289. val == null && (val = seriesItemStyleModel.get(visualName));
  45290. val != null && (visuals[visualName] = val);
  45291. });
  45292. return visuals;
  45293. }
  45294. function calculateColor(visuals) {
  45295. var color = getValueVisualDefine(visuals, 'color');
  45296. if (color) {
  45297. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  45298. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  45299. if (colorSaturation) {
  45300. color = modifyHSL(color, null, null, colorSaturation);
  45301. }
  45302. if (colorAlpha) {
  45303. color = modifyAlpha(color, colorAlpha);
  45304. }
  45305. return color;
  45306. }
  45307. }
  45308. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  45309. return thisNodeColor != null
  45310. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  45311. : null;
  45312. }
  45313. function getValueVisualDefine(visuals, name) {
  45314. var value = visuals[name];
  45315. if (value != null && value !== 'none') {
  45316. return value;
  45317. }
  45318. }
  45319. function buildVisualMapping(
  45320. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  45321. ) {
  45322. if (!viewChildren || !viewChildren.length) {
  45323. return;
  45324. }
  45325. var rangeVisual = getRangeVisual(nodeModel, 'color')
  45326. || (
  45327. visuals.color != null
  45328. && visuals.color !== 'none'
  45329. && (
  45330. getRangeVisual(nodeModel, 'colorAlpha')
  45331. || getRangeVisual(nodeModel, 'colorSaturation')
  45332. )
  45333. );
  45334. if (!rangeVisual) {
  45335. return;
  45336. }
  45337. var visualMin = nodeModel.get('visualMin');
  45338. var visualMax = nodeModel.get('visualMax');
  45339. var dataExtent = nodeLayout.dataExtent.slice();
  45340. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  45341. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  45342. var colorMappingBy = nodeModel.get('colorMappingBy');
  45343. var opt = {
  45344. type: rangeVisual.name,
  45345. dataExtent: dataExtent,
  45346. visual: rangeVisual.range
  45347. };
  45348. if (opt.type === 'color'
  45349. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  45350. ) {
  45351. opt.mappingMethod = 'category';
  45352. opt.loop = true;
  45353. // categories is ordinal, so do not set opt.categories.
  45354. }
  45355. else {
  45356. opt.mappingMethod = 'linear';
  45357. }
  45358. var mapping = new VisualMapping(opt);
  45359. mapping.__drColorMappingBy = colorMappingBy;
  45360. return mapping;
  45361. }
  45362. // Notice: If we dont have the attribute 'colorRange', but only use
  45363. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  45364. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  45365. // this problem will be encountered:
  45366. // If a level-1 node dont have children, and its siblings has children,
  45367. // and colorRange is set on level-1, then the node can not be colored.
  45368. // So we separate 'colorRange' and 'color' to different attributes.
  45369. function getRangeVisual(nodeModel, name) {
  45370. // 'colorRange', 'colorARange', 'colorSRange'.
  45371. // If not exsits on this node, fetch from levels and series.
  45372. var range = nodeModel.get(name);
  45373. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  45374. }
  45375. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  45376. var childVisuals = extend({}, visuals);
  45377. if (mapping) {
  45378. var mappingType = mapping.type;
  45379. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  45380. var value = colorMappingBy === 'index'
  45381. ? index
  45382. : colorMappingBy === 'id'
  45383. ? seriesModel.mapIdToIndex(child.getId())
  45384. : child.getValue(nodeModel.get('visualDimension'));
  45385. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  45386. }
  45387. return childVisuals;
  45388. }
  45389. /*
  45390. * Licensed to the Apache Software Foundation (ASF) under one
  45391. * or more contributor license agreements. See the NOTICE file
  45392. * distributed with this work for additional information
  45393. * regarding copyright ownership. The ASF licenses this file
  45394. * to you under the Apache License, Version 2.0 (the
  45395. * "License"); you may not use this file except in compliance
  45396. * with the License. You may obtain a copy of the License at
  45397. *
  45398. * http://www.apache.org/licenses/LICENSE-2.0
  45399. *
  45400. * Unless required by applicable law or agreed to in writing,
  45401. * software distributed under the License is distributed on an
  45402. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45403. * KIND, either express or implied. See the License for the
  45404. * specific language governing permissions and limitations
  45405. * under the License.
  45406. */
  45407. /*
  45408. * A third-party license is embeded for some of the code in this file:
  45409. * The treemap layout implementation was originally copied from
  45410. * "d3.js" with some modifications made for this project.
  45411. * (See more details in the comment of the method "squarify" below.)
  45412. * The use of the source code of this file is also subject to the terms
  45413. * and consitions of the license of "d3.js" (BSD-3Clause, see
  45414. * </licenses/LICENSE-d3>).
  45415. */
  45416. var mathMax$4 = Math.max;
  45417. var mathMin$4 = Math.min;
  45418. var retrieveValue = retrieve;
  45419. var each$10 = each$1;
  45420. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  45421. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  45422. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  45423. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  45424. /**
  45425. * @public
  45426. */
  45427. var treemapLayout = {
  45428. seriesType: 'treemap',
  45429. reset: function (seriesModel, ecModel, api, payload) {
  45430. // Layout result in each node:
  45431. // {x, y, width, height, area, borderWidth}
  45432. var ecWidth = api.getWidth();
  45433. var ecHeight = api.getHeight();
  45434. var seriesOption = seriesModel.option;
  45435. var layoutInfo = getLayoutRect(
  45436. seriesModel.getBoxLayoutParams(),
  45437. {
  45438. width: api.getWidth(),
  45439. height: api.getHeight()
  45440. }
  45441. );
  45442. var size = seriesOption.size || []; // Compatible with ec2.
  45443. var containerWidth = parsePercent$1(
  45444. retrieveValue(layoutInfo.width, size[0]),
  45445. ecWidth
  45446. );
  45447. var containerHeight = parsePercent$1(
  45448. retrieveValue(layoutInfo.height, size[1]),
  45449. ecHeight
  45450. );
  45451. // Fetch payload info.
  45452. var payloadType = payload && payload.type;
  45453. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  45454. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  45455. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  45456. ? payload.rootRect : null;
  45457. var viewRoot = seriesModel.getViewRoot();
  45458. var viewAbovePath = getPathToRoot(viewRoot);
  45459. if (payloadType !== 'treemapMove') {
  45460. var rootSize = payloadType === 'treemapZoomToNode'
  45461. ? estimateRootSize(
  45462. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  45463. )
  45464. : rootRect
  45465. ? [rootRect.width, rootRect.height]
  45466. : [containerWidth, containerHeight];
  45467. var sort = seriesOption.sort;
  45468. if (sort && sort !== 'asc' && sort !== 'desc') {
  45469. sort = 'desc';
  45470. }
  45471. var options = {
  45472. squareRatio: seriesOption.squareRatio,
  45473. sort: sort,
  45474. leafDepth: seriesOption.leafDepth
  45475. };
  45476. // layout should be cleared because using updateView but not update.
  45477. viewRoot.hostTree.clearLayouts();
  45478. // TODO
  45479. // optimize: if out of view clip, do not layout.
  45480. // But take care that if do not render node out of view clip,
  45481. // how to calculate start po
  45482. var viewRootLayout = {
  45483. x: 0, y: 0,
  45484. width: rootSize[0], height: rootSize[1],
  45485. area: rootSize[0] * rootSize[1]
  45486. };
  45487. viewRoot.setLayout(viewRootLayout);
  45488. squarify(viewRoot, options, false, 0);
  45489. // Supplement layout.
  45490. var viewRootLayout = viewRoot.getLayout();
  45491. each$10(viewAbovePath, function (node, index) {
  45492. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  45493. node.setLayout(extend(
  45494. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  45495. viewRootLayout
  45496. ));
  45497. });
  45498. }
  45499. var treeRoot = seriesModel.getData().tree.root;
  45500. treeRoot.setLayout(
  45501. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  45502. true
  45503. );
  45504. seriesModel.setLayoutInfo(layoutInfo);
  45505. // FIXME
  45506. // 现在没有clip功能,暂时取ec高宽。
  45507. prunning(
  45508. treeRoot,
  45509. // Transform to base element coordinate system.
  45510. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  45511. viewAbovePath,
  45512. viewRoot,
  45513. 0
  45514. );
  45515. }
  45516. };
  45517. /**
  45518. * Layout treemap with squarify algorithm.
  45519. * The original presentation of this algorithm
  45520. * was made by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
  45521. * <https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf>.
  45522. * The implementation of this algorithm was originally copied from "d3.js"
  45523. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/layout/treemap.js>
  45524. * with some modifications made for this program.
  45525. * See the license statement at the head of this file.
  45526. *
  45527. * @protected
  45528. * @param {module:echarts/data/Tree~TreeNode} node
  45529. * @param {Object} options
  45530. * @param {string} options.sort 'asc' or 'desc'
  45531. * @param {number} options.squareRatio
  45532. * @param {boolean} hideChildren
  45533. * @param {number} depth
  45534. */
  45535. function squarify(node, options, hideChildren, depth) {
  45536. var width;
  45537. var height;
  45538. if (node.isRemoved()) {
  45539. return;
  45540. }
  45541. var thisLayout = node.getLayout();
  45542. width = thisLayout.width;
  45543. height = thisLayout.height;
  45544. // Considering border and gap
  45545. var nodeModel = node.getModel();
  45546. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  45547. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  45548. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  45549. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  45550. var layoutOffset = borderWidth - halfGapWidth;
  45551. var layoutOffsetUpper = upperHeight - halfGapWidth;
  45552. var nodeModel = node.getModel();
  45553. node.setLayout({
  45554. borderWidth: borderWidth,
  45555. upperHeight: upperHeight,
  45556. upperLabelHeight: upperLabelHeight
  45557. }, true);
  45558. width = mathMax$4(width - 2 * layoutOffset, 0);
  45559. height = mathMax$4(height - layoutOffset - layoutOffsetUpper, 0);
  45560. var totalArea = width * height;
  45561. var viewChildren = initChildren(
  45562. node, nodeModel, totalArea, options, hideChildren, depth
  45563. );
  45564. if (!viewChildren.length) {
  45565. return;
  45566. }
  45567. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  45568. var rowFixedLength = mathMin$4(width, height);
  45569. var best = Infinity; // the best row score so far
  45570. var row = [];
  45571. row.area = 0;
  45572. for (var i = 0, len = viewChildren.length; i < len;) {
  45573. var child = viewChildren[i];
  45574. row.push(child);
  45575. row.area += child.getLayout().area;
  45576. var score = worst(row, rowFixedLength, options.squareRatio);
  45577. // continue with this orientation
  45578. if (score <= best) {
  45579. i++;
  45580. best = score;
  45581. }
  45582. // abort, and try a different orientation
  45583. else {
  45584. row.area -= row.pop().getLayout().area;
  45585. position(row, rowFixedLength, rect, halfGapWidth, false);
  45586. rowFixedLength = mathMin$4(rect.width, rect.height);
  45587. row.length = row.area = 0;
  45588. best = Infinity;
  45589. }
  45590. }
  45591. if (row.length) {
  45592. position(row, rowFixedLength, rect, halfGapWidth, true);
  45593. }
  45594. if (!hideChildren) {
  45595. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  45596. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  45597. hideChildren = true;
  45598. }
  45599. }
  45600. for (var i = 0, len = viewChildren.length; i < len; i++) {
  45601. squarify(viewChildren[i], options, hideChildren, depth + 1);
  45602. }
  45603. }
  45604. /**
  45605. * Set area to each child, and calculate data extent for visual coding.
  45606. */
  45607. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  45608. var viewChildren = node.children || [];
  45609. var orderBy = options.sort;
  45610. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  45611. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  45612. // leafDepth has higher priority.
  45613. if (hideChildren && !overLeafDepth) {
  45614. return (node.viewChildren = []);
  45615. }
  45616. // Sort children, order by desc.
  45617. viewChildren = filter(viewChildren, function (child) {
  45618. return !child.isRemoved();
  45619. });
  45620. sort$1(viewChildren, orderBy);
  45621. var info = statistic(nodeModel, viewChildren, orderBy);
  45622. if (info.sum === 0) {
  45623. return (node.viewChildren = []);
  45624. }
  45625. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  45626. if (info.sum === 0) {
  45627. return (node.viewChildren = []);
  45628. }
  45629. // Set area to each child.
  45630. for (var i = 0, len = viewChildren.length; i < len; i++) {
  45631. var area = viewChildren[i].getValue() / info.sum * totalArea;
  45632. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  45633. viewChildren[i].setLayout({area: area});
  45634. }
  45635. if (overLeafDepth) {
  45636. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  45637. viewChildren.length = 0;
  45638. }
  45639. node.viewChildren = viewChildren;
  45640. node.setLayout({dataExtent: info.dataExtent}, true);
  45641. return viewChildren;
  45642. }
  45643. /**
  45644. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  45645. */
  45646. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  45647. // visibleMin is not supported yet when no option.sort.
  45648. if (!orderBy) {
  45649. return sum;
  45650. }
  45651. var visibleMin = nodeModel.get('visibleMin');
  45652. var len = orderedChildren.length;
  45653. var deletePoint = len;
  45654. // Always travel from little value to big value.
  45655. for (var i = len - 1; i >= 0; i--) {
  45656. var value = orderedChildren[
  45657. orderBy === 'asc' ? len - i - 1 : i
  45658. ].getValue();
  45659. if (value / sum * totalArea < visibleMin) {
  45660. deletePoint = i;
  45661. sum -= value;
  45662. }
  45663. }
  45664. orderBy === 'asc'
  45665. ? orderedChildren.splice(0, len - deletePoint)
  45666. : orderedChildren.splice(deletePoint, len - deletePoint);
  45667. return sum;
  45668. }
  45669. /**
  45670. * Sort
  45671. */
  45672. function sort$1(viewChildren, orderBy) {
  45673. if (orderBy) {
  45674. viewChildren.sort(function (a, b) {
  45675. var diff = orderBy === 'asc'
  45676. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  45677. return diff === 0
  45678. ? (orderBy === 'asc'
  45679. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  45680. )
  45681. : diff;
  45682. });
  45683. }
  45684. return viewChildren;
  45685. }
  45686. /**
  45687. * Statistic
  45688. */
  45689. function statistic(nodeModel, children, orderBy) {
  45690. // Calculate sum.
  45691. var sum = 0;
  45692. for (var i = 0, len = children.length; i < len; i++) {
  45693. sum += children[i].getValue();
  45694. }
  45695. // Statistic data extent for latter visual coding.
  45696. // Notice: data extent should be calculate based on raw children
  45697. // but not filtered view children, otherwise visual mapping will not
  45698. // be stable when zoom (where children is filtered by visibleMin).
  45699. var dimension = nodeModel.get('visualDimension');
  45700. var dataExtent;
  45701. // The same as area dimension.
  45702. if (!children || !children.length) {
  45703. dataExtent = [NaN, NaN];
  45704. }
  45705. else if (dimension === 'value' && orderBy) {
  45706. dataExtent = [
  45707. children[children.length - 1].getValue(),
  45708. children[0].getValue()
  45709. ];
  45710. orderBy === 'asc' && dataExtent.reverse();
  45711. }
  45712. // Other dimension.
  45713. else {
  45714. var dataExtent = [Infinity, -Infinity];
  45715. each$10(children, function (child) {
  45716. var value = child.getValue(dimension);
  45717. value < dataExtent[0] && (dataExtent[0] = value);
  45718. value > dataExtent[1] && (dataExtent[1] = value);
  45719. });
  45720. }
  45721. return {sum: sum, dataExtent: dataExtent};
  45722. }
  45723. /**
  45724. * Computes the score for the specified row,
  45725. * as the worst aspect ratio.
  45726. */
  45727. function worst(row, rowFixedLength, ratio) {
  45728. var areaMax = 0;
  45729. var areaMin = Infinity;
  45730. for (var i = 0, area, len = row.length; i < len; i++) {
  45731. area = row[i].getLayout().area;
  45732. if (area) {
  45733. area < areaMin && (areaMin = area);
  45734. area > areaMax && (areaMax = area);
  45735. }
  45736. }
  45737. var squareArea = row.area * row.area;
  45738. var f = rowFixedLength * rowFixedLength * ratio;
  45739. return squareArea
  45740. ? mathMax$4(
  45741. (f * areaMax) / squareArea,
  45742. squareArea / (f * areaMin)
  45743. )
  45744. : Infinity;
  45745. }
  45746. /**
  45747. * Positions the specified row of nodes. Modifies `rect`.
  45748. */
  45749. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  45750. // When rowFixedLength === rect.width,
  45751. // it is horizontal subdivision,
  45752. // rowFixedLength is the width of the subdivision,
  45753. // rowOtherLength is the height of the subdivision,
  45754. // and nodes will be positioned from left to right.
  45755. // wh[idx0WhenH] means: when horizontal,
  45756. // wh[idx0WhenH] => wh[0] => 'width'.
  45757. // xy[idx1WhenH] => xy[1] => 'y'.
  45758. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  45759. var idx1WhenH = 1 - idx0WhenH;
  45760. var xy = ['x', 'y'];
  45761. var wh = ['width', 'height'];
  45762. var last = rect[xy[idx0WhenH]];
  45763. var rowOtherLength = rowFixedLength
  45764. ? row.area / rowFixedLength : 0;
  45765. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  45766. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  45767. }
  45768. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  45769. var node = row[i];
  45770. var nodeLayout = {};
  45771. var step = rowOtherLength
  45772. ? node.getLayout().area / rowOtherLength : 0;
  45773. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$4(rowOtherLength - 2 * halfGapWidth, 0);
  45774. // We use Math.max/min to avoid negative width/height when considering gap width.
  45775. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  45776. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  45777. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$4(modWH - 2 * halfGapWidth, 0);
  45778. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$4(halfGapWidth, wh1 / 2);
  45779. nodeLayout[xy[idx0WhenH]] = last + mathMin$4(halfGapWidth, wh0 / 2);
  45780. last += modWH;
  45781. node.setLayout(nodeLayout, true);
  45782. }
  45783. rect[xy[idx1WhenH]] += rowOtherLength;
  45784. rect[wh[idx1WhenH]] -= rowOtherLength;
  45785. }
  45786. // Return [containerWidth, containerHeight] as defualt.
  45787. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  45788. // If targetInfo.node exists, we zoom to the node,
  45789. // so estimate whold width and heigth by target node.
  45790. var currNode = (targetInfo || {}).node;
  45791. var defaultSize = [containerWidth, containerHeight];
  45792. if (!currNode || currNode === viewRoot) {
  45793. return defaultSize;
  45794. }
  45795. var parent;
  45796. var viewArea = containerWidth * containerHeight;
  45797. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  45798. while (parent = currNode.parentNode) { // jshint ignore:line
  45799. var sum = 0;
  45800. var siblings = parent.children;
  45801. for (var i = 0, len = siblings.length; i < len; i++) {
  45802. sum += siblings[i].getValue();
  45803. }
  45804. var currNodeValue = currNode.getValue();
  45805. if (currNodeValue === 0) {
  45806. return defaultSize;
  45807. }
  45808. area *= sum / currNodeValue;
  45809. // Considering border, suppose aspect ratio is 1.
  45810. var parentModel = parent.getModel();
  45811. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  45812. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  45813. area += 4 * borderWidth * borderWidth
  45814. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  45815. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  45816. currNode = parent;
  45817. }
  45818. area < viewArea && (area = viewArea);
  45819. var scale = Math.pow(area / viewArea, 0.5);
  45820. return [containerWidth * scale, containerHeight * scale];
  45821. }
  45822. // Root postion base on coord of containerGroup
  45823. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  45824. if (rootRect) {
  45825. return {x: rootRect.x, y: rootRect.y};
  45826. }
  45827. var defaultPosition = {x: 0, y: 0};
  45828. if (!targetInfo) {
  45829. return defaultPosition;
  45830. }
  45831. // If targetInfo is fetched by 'retrieveTargetInfo',
  45832. // old tree and new tree are the same tree,
  45833. // so the node still exists and we can visit it.
  45834. var targetNode = targetInfo.node;
  45835. var layout = targetNode.getLayout();
  45836. if (!layout) {
  45837. return defaultPosition;
  45838. }
  45839. // Transform coord from local to container.
  45840. var targetCenter = [layout.width / 2, layout.height / 2];
  45841. var node = targetNode;
  45842. while (node) {
  45843. var nodeLayout = node.getLayout();
  45844. targetCenter[0] += nodeLayout.x;
  45845. targetCenter[1] += nodeLayout.y;
  45846. node = node.parentNode;
  45847. }
  45848. return {
  45849. x: layoutInfo.width / 2 - targetCenter[0],
  45850. y: layoutInfo.height / 2 - targetCenter[1]
  45851. };
  45852. }
  45853. // Mark nodes visible for prunning when visual coding and rendering.
  45854. // Prunning depends on layout and root position, so we have to do it after layout.
  45855. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  45856. var nodeLayout = node.getLayout();
  45857. var nodeInViewAbovePath = viewAbovePath[depth];
  45858. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  45859. if (
  45860. (nodeInViewAbovePath && !isAboveViewRoot)
  45861. || (depth === viewAbovePath.length && node !== viewRoot)
  45862. ) {
  45863. return;
  45864. }
  45865. node.setLayout({
  45866. // isInView means: viewRoot sub tree + viewAbovePath
  45867. isInView: true,
  45868. // invisible only means: outside view clip so that the node can not
  45869. // see but still layout for animation preparation but not render.
  45870. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  45871. isAboveViewRoot: isAboveViewRoot
  45872. }, true);
  45873. // Transform to child coordinate.
  45874. var childClipRect = new BoundingRect(
  45875. clipRect.x - nodeLayout.x,
  45876. clipRect.y - nodeLayout.y,
  45877. clipRect.width,
  45878. clipRect.height
  45879. );
  45880. each$10(node.viewChildren || [], function (child) {
  45881. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  45882. });
  45883. }
  45884. function getUpperLabelHeight(model) {
  45885. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  45886. }
  45887. /*
  45888. * Licensed to the Apache Software Foundation (ASF) under one
  45889. * or more contributor license agreements. See the NOTICE file
  45890. * distributed with this work for additional information
  45891. * regarding copyright ownership. The ASF licenses this file
  45892. * to you under the Apache License, Version 2.0 (the
  45893. * "License"); you may not use this file except in compliance
  45894. * with the License. You may obtain a copy of the License at
  45895. *
  45896. * http://www.apache.org/licenses/LICENSE-2.0
  45897. *
  45898. * Unless required by applicable law or agreed to in writing,
  45899. * software distributed under the License is distributed on an
  45900. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45901. * KIND, either express or implied. See the License for the
  45902. * specific language governing permissions and limitations
  45903. * under the License.
  45904. */
  45905. registerVisual(treemapVisual);
  45906. registerLayout(treemapLayout);
  45907. /*
  45908. * Licensed to the Apache Software Foundation (ASF) under one
  45909. * or more contributor license agreements. See the NOTICE file
  45910. * distributed with this work for additional information
  45911. * regarding copyright ownership. The ASF licenses this file
  45912. * to you under the Apache License, Version 2.0 (the
  45913. * "License"); you may not use this file except in compliance
  45914. * with the License. You may obtain a copy of the License at
  45915. *
  45916. * http://www.apache.org/licenses/LICENSE-2.0
  45917. *
  45918. * Unless required by applicable law or agreed to in writing,
  45919. * software distributed under the License is distributed on an
  45920. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45921. * KIND, either express or implied. See the License for the
  45922. * specific language governing permissions and limitations
  45923. * under the License.
  45924. */
  45925. /**
  45926. * Graph data structure
  45927. *
  45928. * @module echarts/data/Graph
  45929. * @author Yi Shen(https://www.github.com/pissang)
  45930. */
  45931. // id may be function name of Object, add a prefix to avoid this problem.
  45932. function generateNodeKey(id) {
  45933. return '_EC_' + id;
  45934. }
  45935. /**
  45936. * @alias module:echarts/data/Graph
  45937. * @constructor
  45938. * @param {boolean} directed
  45939. */
  45940. var Graph = function (directed) {
  45941. /**
  45942. * 是否是有向图
  45943. * @type {boolean}
  45944. * @private
  45945. */
  45946. this._directed = directed || false;
  45947. /**
  45948. * @type {Array.<module:echarts/data/Graph.Node>}
  45949. * @readOnly
  45950. */
  45951. this.nodes = [];
  45952. /**
  45953. * @type {Array.<module:echarts/data/Graph.Edge>}
  45954. * @readOnly
  45955. */
  45956. this.edges = [];
  45957. /**
  45958. * @type {Object.<string, module:echarts/data/Graph.Node>}
  45959. * @private
  45960. */
  45961. this._nodesMap = {};
  45962. /**
  45963. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  45964. * @private
  45965. */
  45966. this._edgesMap = {};
  45967. /**
  45968. * @type {module:echarts/data/List}
  45969. * @readOnly
  45970. */
  45971. this.data;
  45972. /**
  45973. * @type {module:echarts/data/List}
  45974. * @readOnly
  45975. */
  45976. this.edgeData;
  45977. };
  45978. var graphProto = Graph.prototype;
  45979. /**
  45980. * @type {string}
  45981. */
  45982. graphProto.type = 'graph';
  45983. /**
  45984. * If is directed graph
  45985. * @return {boolean}
  45986. */
  45987. graphProto.isDirected = function () {
  45988. return this._directed;
  45989. };
  45990. /**
  45991. * Add a new node
  45992. * @param {string} id
  45993. * @param {number} [dataIndex]
  45994. */
  45995. graphProto.addNode = function (id, dataIndex) {
  45996. id = id || ('' + dataIndex);
  45997. var nodesMap = this._nodesMap;
  45998. if (nodesMap[generateNodeKey(id)]) {
  45999. if (__DEV__) {
  46000. console.error('Graph nodes have duplicate name or id');
  46001. }
  46002. return;
  46003. }
  46004. var node = new Node(id, dataIndex);
  46005. node.hostGraph = this;
  46006. this.nodes.push(node);
  46007. nodesMap[generateNodeKey(id)] = node;
  46008. return node;
  46009. };
  46010. /**
  46011. * Get node by data index
  46012. * @param {number} dataIndex
  46013. * @return {module:echarts/data/Graph~Node}
  46014. */
  46015. graphProto.getNodeByIndex = function (dataIndex) {
  46016. var rawIdx = this.data.getRawIndex(dataIndex);
  46017. return this.nodes[rawIdx];
  46018. };
  46019. /**
  46020. * Get node by id
  46021. * @param {string} id
  46022. * @return {module:echarts/data/Graph.Node}
  46023. */
  46024. graphProto.getNodeById = function (id) {
  46025. return this._nodesMap[generateNodeKey(id)];
  46026. };
  46027. /**
  46028. * Add a new edge
  46029. * @param {number|string|module:echarts/data/Graph.Node} n1
  46030. * @param {number|string|module:echarts/data/Graph.Node} n2
  46031. * @param {number} [dataIndex=-1]
  46032. * @return {module:echarts/data/Graph.Edge}
  46033. */
  46034. graphProto.addEdge = function (n1, n2, dataIndex) {
  46035. var nodesMap = this._nodesMap;
  46036. var edgesMap = this._edgesMap;
  46037. // PNEDING
  46038. if (typeof n1 === 'number') {
  46039. n1 = this.nodes[n1];
  46040. }
  46041. if (typeof n2 === 'number') {
  46042. n2 = this.nodes[n2];
  46043. }
  46044. if (!Node.isInstance(n1)) {
  46045. n1 = nodesMap[generateNodeKey(n1)];
  46046. }
  46047. if (!Node.isInstance(n2)) {
  46048. n2 = nodesMap[generateNodeKey(n2)];
  46049. }
  46050. if (!n1 || !n2) {
  46051. return;
  46052. }
  46053. var key = n1.id + '-' + n2.id;
  46054. // PENDING
  46055. if (edgesMap[key]) {
  46056. return;
  46057. }
  46058. var edge = new Edge(n1, n2, dataIndex);
  46059. edge.hostGraph = this;
  46060. if (this._directed) {
  46061. n1.outEdges.push(edge);
  46062. n2.inEdges.push(edge);
  46063. }
  46064. n1.edges.push(edge);
  46065. if (n1 !== n2) {
  46066. n2.edges.push(edge);
  46067. }
  46068. this.edges.push(edge);
  46069. edgesMap[key] = edge;
  46070. return edge;
  46071. };
  46072. /**
  46073. * Get edge by data index
  46074. * @param {number} dataIndex
  46075. * @return {module:echarts/data/Graph~Node}
  46076. */
  46077. graphProto.getEdgeByIndex = function (dataIndex) {
  46078. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  46079. return this.edges[rawIdx];
  46080. };
  46081. /**
  46082. * Get edge by two linked nodes
  46083. * @param {module:echarts/data/Graph.Node|string} n1
  46084. * @param {module:echarts/data/Graph.Node|string} n2
  46085. * @return {module:echarts/data/Graph.Edge}
  46086. */
  46087. graphProto.getEdge = function (n1, n2) {
  46088. if (Node.isInstance(n1)) {
  46089. n1 = n1.id;
  46090. }
  46091. if (Node.isInstance(n2)) {
  46092. n2 = n2.id;
  46093. }
  46094. var edgesMap = this._edgesMap;
  46095. if (this._directed) {
  46096. return edgesMap[n1 + '-' + n2];
  46097. }
  46098. else {
  46099. return edgesMap[n1 + '-' + n2]
  46100. || edgesMap[n2 + '-' + n1];
  46101. }
  46102. };
  46103. /**
  46104. * Iterate all nodes
  46105. * @param {Function} cb
  46106. * @param {*} [context]
  46107. */
  46108. graphProto.eachNode = function (cb, context) {
  46109. var nodes = this.nodes;
  46110. var len = nodes.length;
  46111. for (var i = 0; i < len; i++) {
  46112. if (nodes[i].dataIndex >= 0) {
  46113. cb.call(context, nodes[i], i);
  46114. }
  46115. }
  46116. };
  46117. /**
  46118. * Iterate all edges
  46119. * @param {Function} cb
  46120. * @param {*} [context]
  46121. */
  46122. graphProto.eachEdge = function (cb, context) {
  46123. var edges = this.edges;
  46124. var len = edges.length;
  46125. for (var i = 0; i < len; i++) {
  46126. if (edges[i].dataIndex >= 0
  46127. && edges[i].node1.dataIndex >= 0
  46128. && edges[i].node2.dataIndex >= 0
  46129. ) {
  46130. cb.call(context, edges[i], i);
  46131. }
  46132. }
  46133. };
  46134. /**
  46135. * Breadth first traverse
  46136. * @param {Function} cb
  46137. * @param {module:echarts/data/Graph.Node} startNode
  46138. * @param {string} [direction='none'] 'none'|'in'|'out'
  46139. * @param {*} [context]
  46140. */
  46141. graphProto.breadthFirstTraverse = function (
  46142. cb, startNode, direction, context
  46143. ) {
  46144. if (!Node.isInstance(startNode)) {
  46145. startNode = this._nodesMap[generateNodeKey(startNode)];
  46146. }
  46147. if (!startNode) {
  46148. return;
  46149. }
  46150. var edgeType = direction === 'out'
  46151. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  46152. for (var i = 0; i < this.nodes.length; i++) {
  46153. this.nodes[i].__visited = false;
  46154. }
  46155. if (cb.call(context, startNode, null)) {
  46156. return;
  46157. }
  46158. var queue = [startNode];
  46159. while (queue.length) {
  46160. var currentNode = queue.shift();
  46161. var edges = currentNode[edgeType];
  46162. for (var i = 0; i < edges.length; i++) {
  46163. var e = edges[i];
  46164. var otherNode = e.node1 === currentNode
  46165. ? e.node2 : e.node1;
  46166. if (!otherNode.__visited) {
  46167. if (cb.call(context, otherNode, currentNode)) {
  46168. // Stop traversing
  46169. return;
  46170. }
  46171. queue.push(otherNode);
  46172. otherNode.__visited = true;
  46173. }
  46174. }
  46175. }
  46176. };
  46177. // TODO
  46178. // graphProto.depthFirstTraverse = function (
  46179. // cb, startNode, direction, context
  46180. // ) {
  46181. // };
  46182. // Filter update
  46183. graphProto.update = function () {
  46184. var data = this.data;
  46185. var edgeData = this.edgeData;
  46186. var nodes = this.nodes;
  46187. var edges = this.edges;
  46188. for (var i = 0, len = nodes.length; i < len; i++) {
  46189. nodes[i].dataIndex = -1;
  46190. }
  46191. for (var i = 0, len = data.count(); i < len; i++) {
  46192. nodes[data.getRawIndex(i)].dataIndex = i;
  46193. }
  46194. edgeData.filterSelf(function (idx) {
  46195. var edge = edges[edgeData.getRawIndex(idx)];
  46196. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  46197. });
  46198. // Update edge
  46199. for (var i = 0, len = edges.length; i < len; i++) {
  46200. edges[i].dataIndex = -1;
  46201. }
  46202. for (var i = 0, len = edgeData.count(); i < len; i++) {
  46203. edges[edgeData.getRawIndex(i)].dataIndex = i;
  46204. }
  46205. };
  46206. /**
  46207. * @return {module:echarts/data/Graph}
  46208. */
  46209. graphProto.clone = function () {
  46210. var graph = new Graph(this._directed);
  46211. var nodes = this.nodes;
  46212. var edges = this.edges;
  46213. for (var i = 0; i < nodes.length; i++) {
  46214. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  46215. }
  46216. for (var i = 0; i < edges.length; i++) {
  46217. var e = edges[i];
  46218. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  46219. }
  46220. return graph;
  46221. };
  46222. /**
  46223. * @alias module:echarts/data/Graph.Node
  46224. */
  46225. function Node(id, dataIndex) {
  46226. /**
  46227. * @type {string}
  46228. */
  46229. this.id = id == null ? '' : id;
  46230. /**
  46231. * @type {Array.<module:echarts/data/Graph.Edge>}
  46232. */
  46233. this.inEdges = [];
  46234. /**
  46235. * @type {Array.<module:echarts/data/Graph.Edge>}
  46236. */
  46237. this.outEdges = [];
  46238. /**
  46239. * @type {Array.<module:echarts/data/Graph.Edge>}
  46240. */
  46241. this.edges = [];
  46242. /**
  46243. * @type {module:echarts/data/Graph}
  46244. */
  46245. this.hostGraph;
  46246. /**
  46247. * @type {number}
  46248. */
  46249. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  46250. }
  46251. Node.prototype = {
  46252. constructor: Node,
  46253. /**
  46254. * @return {number}
  46255. */
  46256. degree: function () {
  46257. return this.edges.length;
  46258. },
  46259. /**
  46260. * @return {number}
  46261. */
  46262. inDegree: function () {
  46263. return this.inEdges.length;
  46264. },
  46265. /**
  46266. * @return {number}
  46267. */
  46268. outDegree: function () {
  46269. return this.outEdges.length;
  46270. },
  46271. /**
  46272. * @param {string} [path]
  46273. * @return {module:echarts/model/Model}
  46274. */
  46275. getModel: function (path) {
  46276. if (this.dataIndex < 0) {
  46277. return;
  46278. }
  46279. var graph = this.hostGraph;
  46280. var itemModel = graph.data.getItemModel(this.dataIndex);
  46281. return itemModel.getModel(path);
  46282. }
  46283. };
  46284. /**
  46285. * 图边
  46286. * @alias module:echarts/data/Graph.Edge
  46287. * @param {module:echarts/data/Graph.Node} n1
  46288. * @param {module:echarts/data/Graph.Node} n2
  46289. * @param {number} [dataIndex=-1]
  46290. */
  46291. function Edge(n1, n2, dataIndex) {
  46292. /**
  46293. * 节点1,如果是有向图则为源节点
  46294. * @type {module:echarts/data/Graph.Node}
  46295. */
  46296. this.node1 = n1;
  46297. /**
  46298. * 节点2,如果是有向图则为目标节点
  46299. * @type {module:echarts/data/Graph.Node}
  46300. */
  46301. this.node2 = n2;
  46302. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  46303. }
  46304. /**
  46305. * @param {string} [path]
  46306. * @return {module:echarts/model/Model}
  46307. */
  46308. Edge.prototype.getModel = function (path) {
  46309. if (this.dataIndex < 0) {
  46310. return;
  46311. }
  46312. var graph = this.hostGraph;
  46313. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  46314. return itemModel.getModel(path);
  46315. };
  46316. var createGraphDataProxyMixin = function (hostName, dataName) {
  46317. return {
  46318. /**
  46319. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  46320. * @return {number}
  46321. */
  46322. getValue: function (dimension) {
  46323. var data = this[hostName][dataName];
  46324. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  46325. },
  46326. /**
  46327. * @param {Object|string} key
  46328. * @param {*} [value]
  46329. */
  46330. setVisual: function (key, value) {
  46331. this.dataIndex >= 0
  46332. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  46333. },
  46334. /**
  46335. * @param {string} key
  46336. * @return {boolean}
  46337. */
  46338. getVisual: function (key, ignoreParent) {
  46339. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  46340. },
  46341. /**
  46342. * @param {Object} layout
  46343. * @return {boolean} [merge=false]
  46344. */
  46345. setLayout: function (layout, merge$$1) {
  46346. this.dataIndex >= 0
  46347. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  46348. },
  46349. /**
  46350. * @return {Object}
  46351. */
  46352. getLayout: function () {
  46353. return this[hostName][dataName].getItemLayout(this.dataIndex);
  46354. },
  46355. /**
  46356. * @return {module:zrender/Element}
  46357. */
  46358. getGraphicEl: function () {
  46359. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  46360. },
  46361. /**
  46362. * @return {number}
  46363. */
  46364. getRawIndex: function () {
  46365. return this[hostName][dataName].getRawIndex(this.dataIndex);
  46366. }
  46367. };
  46368. };
  46369. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  46370. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  46371. Graph.Node = Node;
  46372. Graph.Edge = Edge;
  46373. enableClassCheck(Node);
  46374. enableClassCheck(Edge);
  46375. /*
  46376. * Licensed to the Apache Software Foundation (ASF) under one
  46377. * or more contributor license agreements. See the NOTICE file
  46378. * distributed with this work for additional information
  46379. * regarding copyright ownership. The ASF licenses this file
  46380. * to you under the Apache License, Version 2.0 (the
  46381. * "License"); you may not use this file except in compliance
  46382. * with the License. You may obtain a copy of the License at
  46383. *
  46384. * http://www.apache.org/licenses/LICENSE-2.0
  46385. *
  46386. * Unless required by applicable law or agreed to in writing,
  46387. * software distributed under the License is distributed on an
  46388. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46389. * KIND, either express or implied. See the License for the
  46390. * specific language governing permissions and limitations
  46391. * under the License.
  46392. */
  46393. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  46394. // ??? TODO
  46395. // support dataset?
  46396. var graph = new Graph(directed);
  46397. for (var i = 0; i < nodes.length; i++) {
  46398. graph.addNode(retrieve(
  46399. // Id, name, dataIndex
  46400. nodes[i].id, nodes[i].name, i
  46401. ), i);
  46402. }
  46403. var linkNameList = [];
  46404. var validEdges = [];
  46405. var linkCount = 0;
  46406. for (var i = 0; i < edges.length; i++) {
  46407. var link = edges[i];
  46408. var source = link.source;
  46409. var target = link.target;
  46410. // addEdge may fail when source or target not exists
  46411. if (graph.addEdge(source, target, linkCount)) {
  46412. validEdges.push(link);
  46413. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  46414. linkCount++;
  46415. }
  46416. }
  46417. var coordSys = seriesModel.get('coordinateSystem');
  46418. var nodeData;
  46419. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  46420. nodeData = createListFromArray(nodes, seriesModel);
  46421. }
  46422. else {
  46423. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  46424. var coordDimensions = (coordSysCtor && coordSysCtor.type !== 'view')
  46425. ? (coordSysCtor.dimensions || []) : [];
  46426. // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  46427. // `value` dimension, but graph need `value` dimension. It's better to
  46428. // uniform this behavior.
  46429. if (indexOf(coordDimensions, 'value') < 0) {
  46430. coordDimensions.concat(['value']);
  46431. }
  46432. var dimensionNames = createDimensions(nodes, {
  46433. coordDimensions: coordDimensions
  46434. });
  46435. nodeData = new List(dimensionNames, seriesModel);
  46436. nodeData.initData(nodes);
  46437. }
  46438. var edgeData = new List(['value'], seriesModel);
  46439. edgeData.initData(validEdges, linkNameList);
  46440. beforeLink && beforeLink(nodeData, edgeData);
  46441. linkList({
  46442. mainData: nodeData,
  46443. struct: graph,
  46444. structAttr: 'graph',
  46445. datas: {node: nodeData, edge: edgeData},
  46446. datasAttr: {node: 'data', edge: 'edgeData'}
  46447. });
  46448. // Update dataIndex of nodes and edges because invalid edge may be removed
  46449. graph.update();
  46450. return graph;
  46451. };
  46452. /*
  46453. * Licensed to the Apache Software Foundation (ASF) under one
  46454. * or more contributor license agreements. See the NOTICE file
  46455. * distributed with this work for additional information
  46456. * regarding copyright ownership. The ASF licenses this file
  46457. * to you under the Apache License, Version 2.0 (the
  46458. * "License"); you may not use this file except in compliance
  46459. * with the License. You may obtain a copy of the License at
  46460. *
  46461. * http://www.apache.org/licenses/LICENSE-2.0
  46462. *
  46463. * Unless required by applicable law or agreed to in writing,
  46464. * software distributed under the License is distributed on an
  46465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46466. * KIND, either express or implied. See the License for the
  46467. * specific language governing permissions and limitations
  46468. * under the License.
  46469. */
  46470. var GraphSeries = extendSeriesModel({
  46471. type: 'series.graph',
  46472. init: function (option) {
  46473. GraphSeries.superApply(this, 'init', arguments);
  46474. // Provide data for legend select
  46475. this.legendDataProvider = function () {
  46476. return this._categoriesData;
  46477. };
  46478. this.fillDataTextStyle(option.edges || option.links);
  46479. this._updateCategoriesData();
  46480. },
  46481. mergeOption: function (option) {
  46482. GraphSeries.superApply(this, 'mergeOption', arguments);
  46483. this.fillDataTextStyle(option.edges || option.links);
  46484. this._updateCategoriesData();
  46485. },
  46486. mergeDefaultAndTheme: function (option) {
  46487. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  46488. defaultEmphasis(option, ['edgeLabel'], ['show']);
  46489. },
  46490. getInitialData: function (option, ecModel) {
  46491. var edges = option.edges || option.links || [];
  46492. var nodes = option.data || option.nodes || [];
  46493. var self = this;
  46494. if (nodes && edges) {
  46495. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  46496. }
  46497. function beforeLink(nodeData, edgeData) {
  46498. // Overwrite nodeData.getItemModel to
  46499. nodeData.wrapMethod('getItemModel', function (model) {
  46500. var categoriesModels = self._categoriesModels;
  46501. var categoryIdx = model.getShallow('category');
  46502. var categoryModel = categoriesModels[categoryIdx];
  46503. if (categoryModel) {
  46504. categoryModel.parentModel = model.parentModel;
  46505. model.parentModel = categoryModel;
  46506. }
  46507. return model;
  46508. });
  46509. var edgeLabelModel = self.getModel('edgeLabel');
  46510. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  46511. var fakeSeriesModel = new Model(
  46512. {label: edgeLabelModel.option},
  46513. edgeLabelModel.parentModel,
  46514. ecModel
  46515. );
  46516. var emphasisEdgeLabelModel = self.getModel('emphasis.edgeLabel');
  46517. var emphasisFakeSeriesModel = new Model(
  46518. {emphasis: {label: emphasisEdgeLabelModel.option}},
  46519. emphasisEdgeLabelModel.parentModel,
  46520. ecModel
  46521. );
  46522. edgeData.wrapMethod('getItemModel', function (model) {
  46523. model.customizeGetParent(edgeGetParent);
  46524. return model;
  46525. });
  46526. function edgeGetParent(path) {
  46527. path = this.parsePath(path);
  46528. return (path && path[0] === 'label')
  46529. ? fakeSeriesModel
  46530. : (path && path[0] === 'emphasis' && path[1] === 'label')
  46531. ? emphasisFakeSeriesModel
  46532. : this.parentModel;
  46533. }
  46534. }
  46535. },
  46536. /**
  46537. * @return {module:echarts/data/Graph}
  46538. */
  46539. getGraph: function () {
  46540. return this.getData().graph;
  46541. },
  46542. /**
  46543. * @return {module:echarts/data/List}
  46544. */
  46545. getEdgeData: function () {
  46546. return this.getGraph().edgeData;
  46547. },
  46548. /**
  46549. * @return {module:echarts/data/List}
  46550. */
  46551. getCategoriesData: function () {
  46552. return this._categoriesData;
  46553. },
  46554. /**
  46555. * @override
  46556. */
  46557. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  46558. if (dataType === 'edge') {
  46559. var nodeData = this.getData();
  46560. var params = this.getDataParams(dataIndex, dataType);
  46561. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  46562. var sourceName = nodeData.getName(edge.node1.dataIndex);
  46563. var targetName = nodeData.getName(edge.node2.dataIndex);
  46564. var html = [];
  46565. sourceName != null && html.push(sourceName);
  46566. targetName != null && html.push(targetName);
  46567. html = encodeHTML(html.join(' > '));
  46568. if (params.value) {
  46569. html += ' : ' + encodeHTML(params.value);
  46570. }
  46571. return html;
  46572. }
  46573. else { // dataType === 'node' or empty
  46574. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  46575. }
  46576. },
  46577. _updateCategoriesData: function () {
  46578. var categories = map(this.option.categories || [], function (category) {
  46579. // Data must has value
  46580. return category.value != null ? category : extend({
  46581. value: 0
  46582. }, category);
  46583. });
  46584. var categoriesData = new List(['value'], this);
  46585. categoriesData.initData(categories);
  46586. this._categoriesData = categoriesData;
  46587. this._categoriesModels = categoriesData.mapArray(function (idx) {
  46588. return categoriesData.getItemModel(idx, true);
  46589. });
  46590. },
  46591. setZoom: function (zoom) {
  46592. this.option.zoom = zoom;
  46593. },
  46594. setCenter: function (center) {
  46595. this.option.center = center;
  46596. },
  46597. isAnimationEnabled: function () {
  46598. return GraphSeries.superCall(this, 'isAnimationEnabled')
  46599. // Not enable animation when do force layout
  46600. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  46601. },
  46602. defaultOption: {
  46603. zlevel: 0,
  46604. z: 2,
  46605. coordinateSystem: 'view',
  46606. // Default option for all coordinate systems
  46607. // xAxisIndex: 0,
  46608. // yAxisIndex: 0,
  46609. // polarIndex: 0,
  46610. // geoIndex: 0,
  46611. legendHoverLink: true,
  46612. hoverAnimation: true,
  46613. layout: null,
  46614. focusNodeAdjacency: false,
  46615. // Configuration of circular layout
  46616. circular: {
  46617. rotateLabel: false
  46618. },
  46619. // Configuration of force directed layout
  46620. force: {
  46621. initLayout: null,
  46622. // Node repulsion. Can be an array to represent range.
  46623. repulsion: [0, 50],
  46624. gravity: 0.1,
  46625. // Edge length. Can be an array to represent range.
  46626. edgeLength: 30,
  46627. layoutAnimation: true
  46628. },
  46629. left: 'center',
  46630. top: 'center',
  46631. // right: null,
  46632. // bottom: null,
  46633. // width: '80%',
  46634. // height: '80%',
  46635. symbol: 'circle',
  46636. symbolSize: 10,
  46637. edgeSymbol: ['none', 'none'],
  46638. edgeSymbolSize: 10,
  46639. edgeLabel: {
  46640. position: 'middle'
  46641. },
  46642. draggable: false,
  46643. roam: false,
  46644. // Default on center of graph
  46645. center: null,
  46646. zoom: 1,
  46647. // Symbol size scale ratio in roam
  46648. nodeScaleRatio: 0.6,
  46649. // cursor: null,
  46650. // categories: [],
  46651. // data: []
  46652. // Or
  46653. // nodes: []
  46654. //
  46655. // links: []
  46656. // Or
  46657. // edges: []
  46658. label: {
  46659. show: false,
  46660. formatter: '{b}'
  46661. },
  46662. itemStyle: {},
  46663. lineStyle: {
  46664. color: '#aaa',
  46665. width: 1,
  46666. curveness: 0,
  46667. opacity: 0.5
  46668. },
  46669. emphasis: {
  46670. label: {
  46671. show: true
  46672. }
  46673. }
  46674. }
  46675. });
  46676. /*
  46677. * Licensed to the Apache Software Foundation (ASF) under one
  46678. * or more contributor license agreements. See the NOTICE file
  46679. * distributed with this work for additional information
  46680. * regarding copyright ownership. The ASF licenses this file
  46681. * to you under the Apache License, Version 2.0 (the
  46682. * "License"); you may not use this file except in compliance
  46683. * with the License. You may obtain a copy of the License at
  46684. *
  46685. * http://www.apache.org/licenses/LICENSE-2.0
  46686. *
  46687. * Unless required by applicable law or agreed to in writing,
  46688. * software distributed under the License is distributed on an
  46689. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46690. * KIND, either express or implied. See the License for the
  46691. * specific language governing permissions and limitations
  46692. * under the License.
  46693. */
  46694. /**
  46695. * Line path for bezier and straight line draw
  46696. */
  46697. var straightLineProto = Line.prototype;
  46698. var bezierCurveProto = BezierCurve.prototype;
  46699. function isLine(shape) {
  46700. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  46701. }
  46702. var LinePath = extendShape({
  46703. type: 'ec-line',
  46704. style: {
  46705. stroke: '#000',
  46706. fill: null
  46707. },
  46708. shape: {
  46709. x1: 0,
  46710. y1: 0,
  46711. x2: 0,
  46712. y2: 0,
  46713. percent: 1,
  46714. cpx1: null,
  46715. cpy1: null
  46716. },
  46717. buildPath: function (ctx, shape) {
  46718. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  46719. },
  46720. pointAt: function (t) {
  46721. return isLine(this.shape)
  46722. ? straightLineProto.pointAt.call(this, t)
  46723. : bezierCurveProto.pointAt.call(this, t);
  46724. },
  46725. tangentAt: function (t) {
  46726. var shape = this.shape;
  46727. var p = isLine(shape)
  46728. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  46729. : bezierCurveProto.tangentAt.call(this, t);
  46730. return normalize(p, p);
  46731. }
  46732. });
  46733. /*
  46734. * Licensed to the Apache Software Foundation (ASF) under one
  46735. * or more contributor license agreements. See the NOTICE file
  46736. * distributed with this work for additional information
  46737. * regarding copyright ownership. The ASF licenses this file
  46738. * to you under the Apache License, Version 2.0 (the
  46739. * "License"); you may not use this file except in compliance
  46740. * with the License. You may obtain a copy of the License at
  46741. *
  46742. * http://www.apache.org/licenses/LICENSE-2.0
  46743. *
  46744. * Unless required by applicable law or agreed to in writing,
  46745. * software distributed under the License is distributed on an
  46746. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46747. * KIND, either express or implied. See the License for the
  46748. * specific language governing permissions and limitations
  46749. * under the License.
  46750. */
  46751. /**
  46752. * @module echarts/chart/helper/Line
  46753. */
  46754. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  46755. function makeSymbolTypeKey(symbolCategory) {
  46756. return '_' + symbolCategory + 'Type';
  46757. }
  46758. /**
  46759. * @inner
  46760. */
  46761. function createSymbol$1(name, lineData, idx) {
  46762. var color = lineData.getItemVisual(idx, 'color');
  46763. var symbolType = lineData.getItemVisual(idx, name);
  46764. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  46765. if (!symbolType || symbolType === 'none') {
  46766. return;
  46767. }
  46768. if (!isArray(symbolSize)) {
  46769. symbolSize = [symbolSize, symbolSize];
  46770. }
  46771. var symbolPath = createSymbol(
  46772. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  46773. symbolSize[0], symbolSize[1], color
  46774. );
  46775. symbolPath.name = name;
  46776. return symbolPath;
  46777. }
  46778. function createLine(points) {
  46779. var line = new LinePath({
  46780. name: 'line'
  46781. });
  46782. setLinePoints(line.shape, points);
  46783. return line;
  46784. }
  46785. function setLinePoints(targetShape, points) {
  46786. var p1 = points[0];
  46787. var p2 = points[1];
  46788. var cp1 = points[2];
  46789. targetShape.x1 = p1[0];
  46790. targetShape.y1 = p1[1];
  46791. targetShape.x2 = p2[0];
  46792. targetShape.y2 = p2[1];
  46793. targetShape.percent = 1;
  46794. if (cp1) {
  46795. targetShape.cpx1 = cp1[0];
  46796. targetShape.cpy1 = cp1[1];
  46797. }
  46798. else {
  46799. targetShape.cpx1 = NaN;
  46800. targetShape.cpy1 = NaN;
  46801. }
  46802. }
  46803. function updateSymbolAndLabelBeforeLineUpdate() {
  46804. var lineGroup = this;
  46805. var symbolFrom = lineGroup.childOfName('fromSymbol');
  46806. var symbolTo = lineGroup.childOfName('toSymbol');
  46807. var label = lineGroup.childOfName('label');
  46808. // Quick reject
  46809. if (!symbolFrom && !symbolTo && label.ignore) {
  46810. return;
  46811. }
  46812. var invScale = 1;
  46813. var parentNode = this.parent;
  46814. while (parentNode) {
  46815. if (parentNode.scale) {
  46816. invScale /= parentNode.scale[0];
  46817. }
  46818. parentNode = parentNode.parent;
  46819. }
  46820. var line = lineGroup.childOfName('line');
  46821. // If line not changed
  46822. // FIXME Parent scale changed
  46823. if (!this.__dirty && !line.__dirty) {
  46824. return;
  46825. }
  46826. var percent = line.shape.percent;
  46827. var fromPos = line.pointAt(0);
  46828. var toPos = line.pointAt(percent);
  46829. var d = sub([], toPos, fromPos);
  46830. normalize(d, d);
  46831. if (symbolFrom) {
  46832. symbolFrom.attr('position', fromPos);
  46833. var tangent = line.tangentAt(0);
  46834. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  46835. tangent[1], tangent[0]
  46836. ));
  46837. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  46838. }
  46839. if (symbolTo) {
  46840. symbolTo.attr('position', toPos);
  46841. var tangent = line.tangentAt(1);
  46842. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  46843. tangent[1], tangent[0]
  46844. ));
  46845. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  46846. }
  46847. if (!label.ignore) {
  46848. label.attr('position', toPos);
  46849. var textPosition;
  46850. var textAlign;
  46851. var textVerticalAlign;
  46852. var distance$$1 = 5 * invScale;
  46853. // End
  46854. if (label.__position === 'end') {
  46855. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  46856. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  46857. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  46858. }
  46859. // Middle
  46860. else if (label.__position === 'middle') {
  46861. var halfPercent = percent / 2;
  46862. var tangent = line.tangentAt(halfPercent);
  46863. var n = [tangent[1], -tangent[0]];
  46864. var cp = line.pointAt(halfPercent);
  46865. if (n[1] > 0) {
  46866. n[0] = -n[0];
  46867. n[1] = -n[1];
  46868. }
  46869. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  46870. textAlign = 'center';
  46871. textVerticalAlign = 'bottom';
  46872. var rotation = -Math.atan2(tangent[1], tangent[0]);
  46873. if (toPos[0] < fromPos[0]) {
  46874. rotation = Math.PI + rotation;
  46875. }
  46876. label.attr('rotation', rotation);
  46877. }
  46878. // Start
  46879. else {
  46880. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  46881. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  46882. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  46883. }
  46884. label.attr({
  46885. style: {
  46886. // Use the user specified text align and baseline first
  46887. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  46888. textAlign: label.__textAlign || textAlign
  46889. },
  46890. position: textPosition,
  46891. scale: [invScale, invScale]
  46892. });
  46893. }
  46894. }
  46895. /**
  46896. * @constructor
  46897. * @extends {module:zrender/graphic/Group}
  46898. * @alias {module:echarts/chart/helper/Line}
  46899. */
  46900. function Line$1(lineData, idx, seriesScope) {
  46901. Group.call(this);
  46902. this._createLine(lineData, idx, seriesScope);
  46903. }
  46904. var lineProto = Line$1.prototype;
  46905. // Update symbol position and rotation
  46906. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  46907. lineProto._createLine = function (lineData, idx, seriesScope) {
  46908. var seriesModel = lineData.hostModel;
  46909. var linePoints = lineData.getItemLayout(idx);
  46910. var line = createLine(linePoints);
  46911. line.shape.percent = 0;
  46912. initProps(line, {
  46913. shape: {
  46914. percent: 1
  46915. }
  46916. }, seriesModel, idx);
  46917. this.add(line);
  46918. var label = new Text({
  46919. name: 'label',
  46920. // FIXME
  46921. // Temporary solution for `focusNodeAdjacency`.
  46922. // line label do not use the opacity of lineStyle.
  46923. lineLabelOriginalOpacity: 1
  46924. });
  46925. this.add(label);
  46926. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46927. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  46928. // symbols must added after line to make sure
  46929. // it will be updated after line#update.
  46930. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  46931. this.add(symbol);
  46932. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  46933. }, this);
  46934. this._updateCommonStl(lineData, idx, seriesScope);
  46935. };
  46936. lineProto.updateData = function (lineData, idx, seriesScope) {
  46937. var seriesModel = lineData.hostModel;
  46938. var line = this.childOfName('line');
  46939. var linePoints = lineData.getItemLayout(idx);
  46940. var target = {
  46941. shape: {}
  46942. };
  46943. setLinePoints(target.shape, linePoints);
  46944. updateProps(line, target, seriesModel, idx);
  46945. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46946. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  46947. var key = makeSymbolTypeKey(symbolCategory);
  46948. // Symbol changed
  46949. if (this[key] !== symbolType) {
  46950. this.remove(this.childOfName(symbolCategory));
  46951. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  46952. this.add(symbol);
  46953. }
  46954. this[key] = symbolType;
  46955. }, this);
  46956. this._updateCommonStl(lineData, idx, seriesScope);
  46957. };
  46958. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  46959. var seriesModel = lineData.hostModel;
  46960. var line = this.childOfName('line');
  46961. var lineStyle = seriesScope && seriesScope.lineStyle;
  46962. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  46963. var labelModel = seriesScope && seriesScope.labelModel;
  46964. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  46965. // Optimization for large dataset
  46966. if (!seriesScope || lineData.hasItemOption) {
  46967. var itemModel = lineData.getItemModel(idx);
  46968. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  46969. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  46970. labelModel = itemModel.getModel('label');
  46971. hoverLabelModel = itemModel.getModel('emphasis.label');
  46972. }
  46973. var visualColor = lineData.getItemVisual(idx, 'color');
  46974. var visualOpacity = retrieve3(
  46975. lineData.getItemVisual(idx, 'opacity'),
  46976. lineStyle.opacity,
  46977. 1
  46978. );
  46979. line.useStyle(defaults(
  46980. {
  46981. strokeNoScale: true,
  46982. fill: 'none',
  46983. stroke: visualColor,
  46984. opacity: visualOpacity
  46985. },
  46986. lineStyle
  46987. ));
  46988. line.hoverStyle = hoverLineStyle;
  46989. // Update symbol
  46990. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  46991. var symbol = this.childOfName(symbolCategory);
  46992. if (symbol) {
  46993. symbol.setColor(visualColor);
  46994. symbol.setStyle({
  46995. opacity: visualOpacity
  46996. });
  46997. }
  46998. }, this);
  46999. var showLabel = labelModel.getShallow('show');
  47000. var hoverShowLabel = hoverLabelModel.getShallow('show');
  47001. var label = this.childOfName('label');
  47002. var defaultLabelColor;
  47003. var baseText;
  47004. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  47005. if (showLabel || hoverShowLabel) {
  47006. defaultLabelColor = visualColor || '#000';
  47007. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  47008. if (baseText == null) {
  47009. var rawVal = seriesModel.getRawValue(idx);
  47010. baseText = rawVal == null
  47011. ? lineData.getName(idx)
  47012. : isFinite(rawVal)
  47013. ? round$2(rawVal)
  47014. : rawVal;
  47015. }
  47016. }
  47017. var normalText = showLabel ? baseText : null;
  47018. var emphasisText = hoverShowLabel
  47019. ? retrieve2(
  47020. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  47021. baseText
  47022. )
  47023. : null;
  47024. var labelStyle = label.style;
  47025. // Always set `textStyle` even if `normalStyle.text` is null, because default
  47026. // values have to be set on `normalStyle`.
  47027. if (normalText != null || emphasisText != null) {
  47028. setTextStyle(label.style, labelModel, {
  47029. text: normalText
  47030. }, {
  47031. autoColor: defaultLabelColor
  47032. });
  47033. label.__textAlign = labelStyle.textAlign;
  47034. label.__verticalAlign = labelStyle.textVerticalAlign;
  47035. // 'start', 'middle', 'end'
  47036. label.__position = labelModel.get('position') || 'middle';
  47037. }
  47038. if (emphasisText != null) {
  47039. // Only these properties supported in this emphasis style here.
  47040. label.hoverStyle = {
  47041. text: emphasisText,
  47042. textFill: hoverLabelModel.getTextColor(true),
  47043. // For merging hover style to normal style, do not use
  47044. // `hoverLabelModel.getFont()` here.
  47045. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  47046. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  47047. fontSize: hoverLabelModel.getShallow('fontSize'),
  47048. fontFamily: hoverLabelModel.getShallow('fontFamily')
  47049. };
  47050. }
  47051. else {
  47052. label.hoverStyle = {
  47053. text: null
  47054. };
  47055. }
  47056. label.ignore = !showLabel && !hoverShowLabel;
  47057. setHoverStyle(this);
  47058. };
  47059. lineProto.highlight = function () {
  47060. this.trigger('emphasis');
  47061. };
  47062. lineProto.downplay = function () {
  47063. this.trigger('normal');
  47064. };
  47065. lineProto.updateLayout = function (lineData, idx) {
  47066. this.setLinePoints(lineData.getItemLayout(idx));
  47067. };
  47068. lineProto.setLinePoints = function (points) {
  47069. var linePath = this.childOfName('line');
  47070. setLinePoints(linePath.shape, points);
  47071. linePath.dirty();
  47072. };
  47073. inherits(Line$1, Group);
  47074. /*
  47075. * Licensed to the Apache Software Foundation (ASF) under one
  47076. * or more contributor license agreements. See the NOTICE file
  47077. * distributed with this work for additional information
  47078. * regarding copyright ownership. The ASF licenses this file
  47079. * to you under the Apache License, Version 2.0 (the
  47080. * "License"); you may not use this file except in compliance
  47081. * with the License. You may obtain a copy of the License at
  47082. *
  47083. * http://www.apache.org/licenses/LICENSE-2.0
  47084. *
  47085. * Unless required by applicable law or agreed to in writing,
  47086. * software distributed under the License is distributed on an
  47087. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47088. * KIND, either express or implied. See the License for the
  47089. * specific language governing permissions and limitations
  47090. * under the License.
  47091. */
  47092. /**
  47093. * @module echarts/chart/helper/LineDraw
  47094. */
  47095. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  47096. /**
  47097. * @alias module:echarts/component/marker/LineDraw
  47098. * @constructor
  47099. */
  47100. function LineDraw(ctor) {
  47101. this._ctor = ctor || Line$1;
  47102. this.group = new Group();
  47103. }
  47104. var lineDrawProto = LineDraw.prototype;
  47105. lineDrawProto.isPersistent = function () {
  47106. return true;
  47107. };
  47108. /**
  47109. * @param {module:echarts/data/List} lineData
  47110. */
  47111. lineDrawProto.updateData = function (lineData) {
  47112. var lineDraw = this;
  47113. var group = lineDraw.group;
  47114. var oldLineData = lineDraw._lineData;
  47115. lineDraw._lineData = lineData;
  47116. // There is no oldLineData only when first rendering or switching from
  47117. // stream mode to normal mode, where previous elements should be removed.
  47118. if (!oldLineData) {
  47119. group.removeAll();
  47120. }
  47121. var seriesScope = makeSeriesScope$1(lineData);
  47122. lineData.diff(oldLineData)
  47123. .add(function (idx) {
  47124. doAdd(lineDraw, lineData, idx, seriesScope);
  47125. })
  47126. .update(function (newIdx, oldIdx) {
  47127. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  47128. })
  47129. .remove(function (idx) {
  47130. group.remove(oldLineData.getItemGraphicEl(idx));
  47131. })
  47132. .execute();
  47133. };
  47134. function doAdd(lineDraw, lineData, idx, seriesScope) {
  47135. var itemLayout = lineData.getItemLayout(idx);
  47136. if (!lineNeedsDraw(itemLayout)) {
  47137. return;
  47138. }
  47139. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  47140. lineData.setItemGraphicEl(idx, el);
  47141. lineDraw.group.add(el);
  47142. }
  47143. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  47144. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  47145. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  47146. lineDraw.group.remove(itemEl);
  47147. return;
  47148. }
  47149. if (!itemEl) {
  47150. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  47151. }
  47152. else {
  47153. itemEl.updateData(newLineData, newIdx, seriesScope);
  47154. }
  47155. newLineData.setItemGraphicEl(newIdx, itemEl);
  47156. lineDraw.group.add(itemEl);
  47157. }
  47158. lineDrawProto.updateLayout = function () {
  47159. var lineData = this._lineData;
  47160. // Do not support update layout in incremental mode.
  47161. if (!lineData) {
  47162. return;
  47163. }
  47164. lineData.eachItemGraphicEl(function (el, idx) {
  47165. el.updateLayout(lineData, idx);
  47166. }, this);
  47167. };
  47168. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  47169. this._seriesScope = makeSeriesScope$1(lineData);
  47170. this._lineData = null;
  47171. this.group.removeAll();
  47172. };
  47173. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  47174. function updateIncrementalAndHover(el) {
  47175. if (!el.isGroup) {
  47176. el.incremental = el.useHoverLayer = true;
  47177. }
  47178. }
  47179. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  47180. var itemLayout = lineData.getItemLayout(idx);
  47181. if (lineNeedsDraw(itemLayout)) {
  47182. var el = new this._ctor(lineData, idx, this._seriesScope);
  47183. el.traverse(updateIncrementalAndHover);
  47184. this.group.add(el);
  47185. lineData.setItemGraphicEl(idx, el);
  47186. }
  47187. }
  47188. };
  47189. function makeSeriesScope$1(lineData) {
  47190. var hostModel = lineData.hostModel;
  47191. return {
  47192. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  47193. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  47194. labelModel: hostModel.getModel('label'),
  47195. hoverLabelModel: hostModel.getModel('emphasis.label')
  47196. };
  47197. }
  47198. lineDrawProto.remove = function () {
  47199. this._clearIncremental();
  47200. this._incremental = null;
  47201. this.group.removeAll();
  47202. };
  47203. lineDrawProto._clearIncremental = function () {
  47204. var incremental = this._incremental;
  47205. if (incremental) {
  47206. incremental.clearDisplaybles();
  47207. }
  47208. };
  47209. function isPointNaN(pt) {
  47210. return isNaN(pt[0]) || isNaN(pt[1]);
  47211. }
  47212. function lineNeedsDraw(pts) {
  47213. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  47214. }
  47215. /*
  47216. * Licensed to the Apache Software Foundation (ASF) under one
  47217. * or more contributor license agreements. See the NOTICE file
  47218. * distributed with this work for additional information
  47219. * regarding copyright ownership. The ASF licenses this file
  47220. * to you under the Apache License, Version 2.0 (the
  47221. * "License"); you may not use this file except in compliance
  47222. * with the License. You may obtain a copy of the License at
  47223. *
  47224. * http://www.apache.org/licenses/LICENSE-2.0
  47225. *
  47226. * Unless required by applicable law or agreed to in writing,
  47227. * software distributed under the License is distributed on an
  47228. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47229. * KIND, either express or implied. See the License for the
  47230. * specific language governing permissions and limitations
  47231. * under the License.
  47232. */
  47233. var v1 = [];
  47234. var v2 = [];
  47235. var v3 = [];
  47236. var quadraticAt$1 = quadraticAt;
  47237. var v2DistSquare = distSquare;
  47238. var mathAbs$1 = Math.abs;
  47239. function intersectCurveCircle(curvePoints, center, radius) {
  47240. var p0 = curvePoints[0];
  47241. var p1 = curvePoints[1];
  47242. var p2 = curvePoints[2];
  47243. var d = Infinity;
  47244. var t;
  47245. var radiusSquare = radius * radius;
  47246. var interval = 0.1;
  47247. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  47248. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  47249. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  47250. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  47251. if (diff < d) {
  47252. d = diff;
  47253. t = _t;
  47254. }
  47255. }
  47256. // Assume the segment is monotone,Find root through Bisection method
  47257. // At most 32 iteration
  47258. for (var i = 0; i < 32; i++) {
  47259. // var prev = t - interval;
  47260. var next = t + interval;
  47261. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  47262. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  47263. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  47264. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  47265. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  47266. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  47267. var diff = v2DistSquare(v2, center) - radiusSquare;
  47268. if (mathAbs$1(diff) < 1e-2) {
  47269. break;
  47270. }
  47271. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  47272. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  47273. interval /= 2;
  47274. if (diff < 0) {
  47275. if (nextDiff >= 0) {
  47276. t = t + interval;
  47277. }
  47278. else {
  47279. t = t - interval;
  47280. }
  47281. }
  47282. else {
  47283. if (nextDiff >= 0) {
  47284. t = t - interval;
  47285. }
  47286. else {
  47287. t = t + interval;
  47288. }
  47289. }
  47290. }
  47291. return t;
  47292. }
  47293. // Adjust edge to avoid
  47294. var adjustEdge = function (graph, scale$$1) {
  47295. var tmp0 = [];
  47296. var quadraticSubdivide$$1 = quadraticSubdivide;
  47297. var pts = [[], [], []];
  47298. var pts2 = [[], []];
  47299. var v = [];
  47300. scale$$1 /= 2;
  47301. function getSymbolSize(node) {
  47302. var symbolSize = node.getVisual('symbolSize');
  47303. if (symbolSize instanceof Array) {
  47304. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  47305. }
  47306. return symbolSize;
  47307. }
  47308. graph.eachEdge(function (edge, idx) {
  47309. var linePoints = edge.getLayout();
  47310. var fromSymbol = edge.getVisual('fromSymbol');
  47311. var toSymbol = edge.getVisual('toSymbol');
  47312. if (!linePoints.__original) {
  47313. linePoints.__original = [
  47314. clone$1(linePoints[0]),
  47315. clone$1(linePoints[1])
  47316. ];
  47317. if (linePoints[2]) {
  47318. linePoints.__original.push(clone$1(linePoints[2]));
  47319. }
  47320. }
  47321. var originalPoints = linePoints.__original;
  47322. // Quadratic curve
  47323. if (linePoints[2] != null) {
  47324. copy(pts[0], originalPoints[0]);
  47325. copy(pts[1], originalPoints[2]);
  47326. copy(pts[2], originalPoints[1]);
  47327. if (fromSymbol && fromSymbol !== 'none') {
  47328. var symbolSize = getSymbolSize(edge.node1);
  47329. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  47330. // Subdivide and get the second
  47331. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  47332. pts[0][0] = tmp0[3];
  47333. pts[1][0] = tmp0[4];
  47334. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  47335. pts[0][1] = tmp0[3];
  47336. pts[1][1] = tmp0[4];
  47337. }
  47338. if (toSymbol && toSymbol !== 'none') {
  47339. var symbolSize = getSymbolSize(edge.node2);
  47340. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  47341. // Subdivide and get the first
  47342. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  47343. pts[1][0] = tmp0[1];
  47344. pts[2][0] = tmp0[2];
  47345. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  47346. pts[1][1] = tmp0[1];
  47347. pts[2][1] = tmp0[2];
  47348. }
  47349. // Copy back to layout
  47350. copy(linePoints[0], pts[0]);
  47351. copy(linePoints[1], pts[2]);
  47352. copy(linePoints[2], pts[1]);
  47353. }
  47354. // Line
  47355. else {
  47356. copy(pts2[0], originalPoints[0]);
  47357. copy(pts2[1], originalPoints[1]);
  47358. sub(v, pts2[1], pts2[0]);
  47359. normalize(v, v);
  47360. if (fromSymbol && fromSymbol !== 'none') {
  47361. var symbolSize = getSymbolSize(edge.node1);
  47362. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  47363. }
  47364. if (toSymbol && toSymbol !== 'none') {
  47365. var symbolSize = getSymbolSize(edge.node2);
  47366. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  47367. }
  47368. copy(linePoints[0], pts2[0]);
  47369. copy(linePoints[1], pts2[1]);
  47370. }
  47371. });
  47372. };
  47373. /*
  47374. * Licensed to the Apache Software Foundation (ASF) under one
  47375. * or more contributor license agreements. See the NOTICE file
  47376. * distributed with this work for additional information
  47377. * regarding copyright ownership. The ASF licenses this file
  47378. * to you under the Apache License, Version 2.0 (the
  47379. * "License"); you may not use this file except in compliance
  47380. * with the License. You may obtain a copy of the License at
  47381. *
  47382. * http://www.apache.org/licenses/LICENSE-2.0
  47383. *
  47384. * Unless required by applicable law or agreed to in writing,
  47385. * software distributed under the License is distributed on an
  47386. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47387. * KIND, either express or implied. See the License for the
  47388. * specific language governing permissions and limitations
  47389. * under the License.
  47390. */
  47391. var FOCUS_ADJACENCY = '__focusNodeAdjacency';
  47392. var UNFOCUS_ADJACENCY = '__unfocusNodeAdjacency';
  47393. var nodeOpacityPath = ['itemStyle', 'opacity'];
  47394. var lineOpacityPath = ['lineStyle', 'opacity'];
  47395. function getItemOpacity(item, opacityPath) {
  47396. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  47397. }
  47398. function fadeOutItem(item, opacityPath, opacityRatio) {
  47399. var el = item.getGraphicEl();
  47400. var opacity = getItemOpacity(item, opacityPath);
  47401. if (opacityRatio != null) {
  47402. opacity == null && (opacity = 1);
  47403. opacity *= opacityRatio;
  47404. }
  47405. el.downplay && el.downplay();
  47406. el.traverse(function (child) {
  47407. if (child.type !== 'group') {
  47408. var opct = child.lineLabelOriginalOpacity;
  47409. if (opct == null || opacityRatio != null) {
  47410. opct = opacity;
  47411. }
  47412. child.setStyle('opacity', opct);
  47413. }
  47414. });
  47415. }
  47416. function fadeInItem(item, opacityPath) {
  47417. var opacity = getItemOpacity(item, opacityPath);
  47418. var el = item.getGraphicEl();
  47419. el.highlight && el.highlight();
  47420. el.traverse(function (child) {
  47421. if (child.type !== 'group') {
  47422. child.setStyle('opacity', opacity);
  47423. }
  47424. });
  47425. }
  47426. extendChartView({
  47427. type: 'graph',
  47428. init: function (ecModel, api) {
  47429. var symbolDraw = new SymbolDraw();
  47430. var lineDraw = new LineDraw();
  47431. var group = this.group;
  47432. this._controller = new RoamController(api.getZr());
  47433. this._controllerHost = {target: group};
  47434. group.add(symbolDraw.group);
  47435. group.add(lineDraw.group);
  47436. this._symbolDraw = symbolDraw;
  47437. this._lineDraw = lineDraw;
  47438. this._firstRender = true;
  47439. },
  47440. render: function (seriesModel, ecModel, api) {
  47441. var coordSys = seriesModel.coordinateSystem;
  47442. this._model = seriesModel;
  47443. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  47444. var symbolDraw = this._symbolDraw;
  47445. var lineDraw = this._lineDraw;
  47446. var group = this.group;
  47447. if (coordSys.type === 'view') {
  47448. var groupNewProp = {
  47449. position: coordSys.position,
  47450. scale: coordSys.scale
  47451. };
  47452. if (this._firstRender) {
  47453. group.attr(groupNewProp);
  47454. }
  47455. else {
  47456. updateProps(group, groupNewProp, seriesModel);
  47457. }
  47458. }
  47459. // Fix edge contact point with node
  47460. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  47461. var data = seriesModel.getData();
  47462. symbolDraw.updateData(data);
  47463. var edgeData = seriesModel.getEdgeData();
  47464. lineDraw.updateData(edgeData);
  47465. this._updateNodeAndLinkScale();
  47466. this._updateController(seriesModel, ecModel, api);
  47467. clearTimeout(this._layoutTimeout);
  47468. var forceLayout = seriesModel.forceLayout;
  47469. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  47470. if (forceLayout) {
  47471. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  47472. }
  47473. data.eachItemGraphicEl(function (el, idx) {
  47474. var itemModel = data.getItemModel(idx);
  47475. // Update draggable
  47476. el.off('drag').off('dragend');
  47477. var draggable = itemModel.get('draggable');
  47478. if (draggable) {
  47479. el.on('drag', function () {
  47480. if (forceLayout) {
  47481. forceLayout.warmUp();
  47482. !this._layouting
  47483. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  47484. forceLayout.setFixed(idx);
  47485. // Write position back to layout
  47486. data.setItemLayout(idx, el.position);
  47487. }
  47488. }, this).on('dragend', function () {
  47489. if (forceLayout) {
  47490. forceLayout.setUnfixed(idx);
  47491. }
  47492. }, this);
  47493. }
  47494. el.setDraggable(draggable && forceLayout);
  47495. el[FOCUS_ADJACENCY] && el.off('mouseover', el[FOCUS_ADJACENCY]);
  47496. el[UNFOCUS_ADJACENCY] && el.off('mouseout', el[UNFOCUS_ADJACENCY]);
  47497. if (itemModel.get('focusNodeAdjacency')) {
  47498. el.on('mouseover', el[FOCUS_ADJACENCY] = function () {
  47499. api.dispatchAction({
  47500. type: 'focusNodeAdjacency',
  47501. seriesId: seriesModel.id,
  47502. dataIndex: el.dataIndex
  47503. });
  47504. });
  47505. el.on('mouseout', el[UNFOCUS_ADJACENCY] = function () {
  47506. api.dispatchAction({
  47507. type: 'unfocusNodeAdjacency',
  47508. seriesId: seriesModel.id
  47509. });
  47510. });
  47511. }
  47512. }, this);
  47513. data.graph.eachEdge(function (edge) {
  47514. var el = edge.getGraphicEl();
  47515. el[FOCUS_ADJACENCY] && el.off('mouseover', el[FOCUS_ADJACENCY]);
  47516. el[UNFOCUS_ADJACENCY] && el.off('mouseout', el[UNFOCUS_ADJACENCY]);
  47517. if (edge.getModel().get('focusNodeAdjacency')) {
  47518. el.on('mouseover', el[FOCUS_ADJACENCY] = function () {
  47519. api.dispatchAction({
  47520. type: 'focusNodeAdjacency',
  47521. seriesId: seriesModel.id,
  47522. edgeDataIndex: edge.dataIndex
  47523. });
  47524. });
  47525. el.on('mouseout', el[UNFOCUS_ADJACENCY] = function () {
  47526. api.dispatchAction({
  47527. type: 'unfocusNodeAdjacency',
  47528. seriesId: seriesModel.id
  47529. });
  47530. });
  47531. }
  47532. });
  47533. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  47534. && seriesModel.get('circular.rotateLabel');
  47535. var cx = data.getLayout('cx');
  47536. var cy = data.getLayout('cy');
  47537. data.eachItemGraphicEl(function (el, idx) {
  47538. var symbolPath = el.getSymbolPath();
  47539. if (circularRotateLabel) {
  47540. var pos = data.getItemLayout(idx);
  47541. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  47542. if (rad < 0) {
  47543. rad = Math.PI * 2 + rad;
  47544. }
  47545. var isLeft = pos[0] < cx;
  47546. if (isLeft) {
  47547. rad = rad - Math.PI;
  47548. }
  47549. var textPosition = isLeft ? 'left' : 'right';
  47550. symbolPath.setStyle({
  47551. textRotation: -rad,
  47552. textPosition: textPosition,
  47553. textOrigin: 'center'
  47554. });
  47555. symbolPath.hoverStyle && (symbolPath.hoverStyle.textPosition = textPosition);
  47556. }
  47557. else {
  47558. symbolPath.setStyle({
  47559. textRotation: 0
  47560. });
  47561. }
  47562. });
  47563. this._firstRender = false;
  47564. },
  47565. dispose: function () {
  47566. this._controller && this._controller.dispose();
  47567. this._controllerHost = {};
  47568. },
  47569. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  47570. var data = this._model.getData();
  47571. var graph = data.graph;
  47572. var dataIndex = payload.dataIndex;
  47573. var edgeDataIndex = payload.edgeDataIndex;
  47574. var node = graph.getNodeByIndex(dataIndex);
  47575. var edge = graph.getEdgeByIndex(edgeDataIndex);
  47576. if (!node && !edge) {
  47577. return;
  47578. }
  47579. graph.eachNode(function (node) {
  47580. fadeOutItem(node, nodeOpacityPath, 0.1);
  47581. });
  47582. graph.eachEdge(function (edge) {
  47583. fadeOutItem(edge, lineOpacityPath, 0.1);
  47584. });
  47585. if (node) {
  47586. fadeInItem(node, nodeOpacityPath);
  47587. each$1(node.edges, function (adjacentEdge) {
  47588. if (adjacentEdge.dataIndex < 0) {
  47589. return;
  47590. }
  47591. fadeInItem(adjacentEdge, lineOpacityPath);
  47592. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  47593. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  47594. });
  47595. }
  47596. if (edge) {
  47597. fadeInItem(edge, lineOpacityPath);
  47598. fadeInItem(edge.node1, nodeOpacityPath);
  47599. fadeInItem(edge.node2, nodeOpacityPath);
  47600. }
  47601. },
  47602. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  47603. var graph = this._model.getData().graph;
  47604. graph.eachNode(function (node) {
  47605. fadeOutItem(node, nodeOpacityPath);
  47606. });
  47607. graph.eachEdge(function (edge) {
  47608. fadeOutItem(edge, lineOpacityPath);
  47609. });
  47610. },
  47611. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  47612. var self = this;
  47613. (function step() {
  47614. forceLayout.step(function (stopped) {
  47615. self.updateLayout(self._model);
  47616. (self._layouting = !stopped) && (
  47617. layoutAnimation
  47618. ? (self._layoutTimeout = setTimeout(step, 16))
  47619. : step()
  47620. );
  47621. });
  47622. })();
  47623. },
  47624. _updateController: function (seriesModel, ecModel, api) {
  47625. var controller = this._controller;
  47626. var controllerHost = this._controllerHost;
  47627. var group = this.group;
  47628. controller.setPointerChecker(function (e, x, y) {
  47629. var rect = group.getBoundingRect();
  47630. rect.applyTransform(group.transform);
  47631. return rect.contain(x, y)
  47632. && !onIrrelevantElement(e, api, seriesModel);
  47633. });
  47634. if (seriesModel.coordinateSystem.type !== 'view') {
  47635. controller.disable();
  47636. return;
  47637. }
  47638. controller.enable(seriesModel.get('roam'));
  47639. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  47640. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  47641. controller
  47642. .off('pan')
  47643. .off('zoom')
  47644. .on('pan', function (e) {
  47645. updateViewOnPan(controllerHost, e.dx, e.dy);
  47646. api.dispatchAction({
  47647. seriesId: seriesModel.id,
  47648. type: 'graphRoam',
  47649. dx: e.dx,
  47650. dy: e.dy
  47651. });
  47652. })
  47653. .on('zoom', function (e) {
  47654. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  47655. api.dispatchAction({
  47656. seriesId: seriesModel.id,
  47657. type: 'graphRoam',
  47658. zoom: e.scale,
  47659. originX: e.originX,
  47660. originY: e.originY
  47661. });
  47662. this._updateNodeAndLinkScale();
  47663. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  47664. this._lineDraw.updateLayout();
  47665. }, this);
  47666. },
  47667. _updateNodeAndLinkScale: function () {
  47668. var seriesModel = this._model;
  47669. var data = seriesModel.getData();
  47670. var nodeScale = this._getNodeGlobalScale(seriesModel);
  47671. var invScale = [nodeScale, nodeScale];
  47672. data.eachItemGraphicEl(function (el, idx) {
  47673. el.attr('scale', invScale);
  47674. });
  47675. },
  47676. _getNodeGlobalScale: function (seriesModel) {
  47677. var coordSys = seriesModel.coordinateSystem;
  47678. if (coordSys.type !== 'view') {
  47679. return 1;
  47680. }
  47681. var nodeScaleRatio = this._nodeScaleRatio;
  47682. var groupScale = coordSys.scale;
  47683. var groupZoom = (groupScale && groupScale[0]) || 1;
  47684. // Scale node when zoom changes
  47685. var roamZoom = coordSys.getZoom();
  47686. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  47687. return nodeScale / groupZoom;
  47688. },
  47689. updateLayout: function (seriesModel) {
  47690. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  47691. this._symbolDraw.updateLayout();
  47692. this._lineDraw.updateLayout();
  47693. },
  47694. remove: function (ecModel, api) {
  47695. this._symbolDraw && this._symbolDraw.remove();
  47696. this._lineDraw && this._lineDraw.remove();
  47697. }
  47698. });
  47699. /*
  47700. * Licensed to the Apache Software Foundation (ASF) under one
  47701. * or more contributor license agreements. See the NOTICE file
  47702. * distributed with this work for additional information
  47703. * regarding copyright ownership. The ASF licenses this file
  47704. * to you under the Apache License, Version 2.0 (the
  47705. * "License"); you may not use this file except in compliance
  47706. * with the License. You may obtain a copy of the License at
  47707. *
  47708. * http://www.apache.org/licenses/LICENSE-2.0
  47709. *
  47710. * Unless required by applicable law or agreed to in writing,
  47711. * software distributed under the License is distributed on an
  47712. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47713. * KIND, either express or implied. See the License for the
  47714. * specific language governing permissions and limitations
  47715. * under the License.
  47716. */
  47717. /**
  47718. * @payload
  47719. * @property {number} [seriesIndex]
  47720. * @property {string} [seriesId]
  47721. * @property {string} [seriesName]
  47722. * @property {number} [dataIndex]
  47723. */
  47724. registerAction({
  47725. type: 'focusNodeAdjacency',
  47726. event: 'focusNodeAdjacency',
  47727. update: 'series:focusNodeAdjacency'
  47728. }, function () {});
  47729. /**
  47730. * @payload
  47731. * @property {number} [seriesIndex]
  47732. * @property {string} [seriesId]
  47733. * @property {string} [seriesName]
  47734. */
  47735. registerAction({
  47736. type: 'unfocusNodeAdjacency',
  47737. event: 'unfocusNodeAdjacency',
  47738. update: 'series:unfocusNodeAdjacency'
  47739. }, function () {});
  47740. /*
  47741. * Licensed to the Apache Software Foundation (ASF) under one
  47742. * or more contributor license agreements. See the NOTICE file
  47743. * distributed with this work for additional information
  47744. * regarding copyright ownership. The ASF licenses this file
  47745. * to you under the Apache License, Version 2.0 (the
  47746. * "License"); you may not use this file except in compliance
  47747. * with the License. You may obtain a copy of the License at
  47748. *
  47749. * http://www.apache.org/licenses/LICENSE-2.0
  47750. *
  47751. * Unless required by applicable law or agreed to in writing,
  47752. * software distributed under the License is distributed on an
  47753. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47754. * KIND, either express or implied. See the License for the
  47755. * specific language governing permissions and limitations
  47756. * under the License.
  47757. */
  47758. var actionInfo = {
  47759. type: 'graphRoam',
  47760. event: 'graphRoam',
  47761. update: 'none'
  47762. };
  47763. /**
  47764. * @payload
  47765. * @property {string} name Series name
  47766. * @property {number} [dx]
  47767. * @property {number} [dy]
  47768. * @property {number} [zoom]
  47769. * @property {number} [originX]
  47770. * @property {number} [originY]
  47771. */
  47772. registerAction(actionInfo, function (payload, ecModel) {
  47773. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  47774. var coordSys = seriesModel.coordinateSystem;
  47775. var res = updateCenterAndZoom(coordSys, payload);
  47776. seriesModel.setCenter
  47777. && seriesModel.setCenter(res.center);
  47778. seriesModel.setZoom
  47779. && seriesModel.setZoom(res.zoom);
  47780. });
  47781. });
  47782. /*
  47783. * Licensed to the Apache Software Foundation (ASF) under one
  47784. * or more contributor license agreements. See the NOTICE file
  47785. * distributed with this work for additional information
  47786. * regarding copyright ownership. The ASF licenses this file
  47787. * to you under the Apache License, Version 2.0 (the
  47788. * "License"); you may not use this file except in compliance
  47789. * with the License. You may obtain a copy of the License at
  47790. *
  47791. * http://www.apache.org/licenses/LICENSE-2.0
  47792. *
  47793. * Unless required by applicable law or agreed to in writing,
  47794. * software distributed under the License is distributed on an
  47795. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47796. * KIND, either express or implied. See the License for the
  47797. * specific language governing permissions and limitations
  47798. * under the License.
  47799. */
  47800. var categoryFilter = function (ecModel) {
  47801. var legendModels = ecModel.findComponents({
  47802. mainType: 'legend'
  47803. });
  47804. if (!legendModels || !legendModels.length) {
  47805. return;
  47806. }
  47807. ecModel.eachSeriesByType('graph', function (graphSeries) {
  47808. var categoriesData = graphSeries.getCategoriesData();
  47809. var graph = graphSeries.getGraph();
  47810. var data = graph.data;
  47811. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  47812. data.filterSelf(function (idx) {
  47813. var model = data.getItemModel(idx);
  47814. var category = model.getShallow('category');
  47815. if (category != null) {
  47816. if (typeof category === 'number') {
  47817. category = categoryNames[category];
  47818. }
  47819. // If in any legend component the status is not selected.
  47820. for (var i = 0; i < legendModels.length; i++) {
  47821. if (!legendModels[i].isSelected(category)) {
  47822. return false;
  47823. }
  47824. }
  47825. }
  47826. return true;
  47827. });
  47828. }, this);
  47829. };
  47830. /*
  47831. * Licensed to the Apache Software Foundation (ASF) under one
  47832. * or more contributor license agreements. See the NOTICE file
  47833. * distributed with this work for additional information
  47834. * regarding copyright ownership. The ASF licenses this file
  47835. * to you under the Apache License, Version 2.0 (the
  47836. * "License"); you may not use this file except in compliance
  47837. * with the License. You may obtain a copy of the License at
  47838. *
  47839. * http://www.apache.org/licenses/LICENSE-2.0
  47840. *
  47841. * Unless required by applicable law or agreed to in writing,
  47842. * software distributed under the License is distributed on an
  47843. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47844. * KIND, either express or implied. See the License for the
  47845. * specific language governing permissions and limitations
  47846. * under the License.
  47847. */
  47848. var categoryVisual = function (ecModel) {
  47849. var paletteScope = {};
  47850. ecModel.eachSeriesByType('graph', function (seriesModel) {
  47851. var categoriesData = seriesModel.getCategoriesData();
  47852. var data = seriesModel.getData();
  47853. var categoryNameIdxMap = {};
  47854. categoriesData.each(function (idx) {
  47855. var name = categoriesData.getName(idx);
  47856. // Add prefix to avoid conflict with Object.prototype.
  47857. categoryNameIdxMap['ec-' + name] = idx;
  47858. var itemModel = categoriesData.getItemModel(idx);
  47859. var color = itemModel.get('itemStyle.color')
  47860. || seriesModel.getColorFromPalette(name, paletteScope);
  47861. categoriesData.setItemVisual(idx, 'color', color);
  47862. });
  47863. // Assign category color to visual
  47864. if (categoriesData.count()) {
  47865. data.each(function (idx) {
  47866. var model = data.getItemModel(idx);
  47867. var category = model.getShallow('category');
  47868. if (category != null) {
  47869. if (typeof category === 'string') {
  47870. category = categoryNameIdxMap['ec-' + category];
  47871. }
  47872. if (!data.getItemVisual(idx, 'color', true)) {
  47873. data.setItemVisual(
  47874. idx, 'color',
  47875. categoriesData.getItemVisual(category, 'color')
  47876. );
  47877. }
  47878. }
  47879. });
  47880. }
  47881. });
  47882. };
  47883. /*
  47884. * Licensed to the Apache Software Foundation (ASF) under one
  47885. * or more contributor license agreements. See the NOTICE file
  47886. * distributed with this work for additional information
  47887. * regarding copyright ownership. The ASF licenses this file
  47888. * to you under the Apache License, Version 2.0 (the
  47889. * "License"); you may not use this file except in compliance
  47890. * with the License. You may obtain a copy of the License at
  47891. *
  47892. * http://www.apache.org/licenses/LICENSE-2.0
  47893. *
  47894. * Unless required by applicable law or agreed to in writing,
  47895. * software distributed under the License is distributed on an
  47896. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47897. * KIND, either express or implied. See the License for the
  47898. * specific language governing permissions and limitations
  47899. * under the License.
  47900. */
  47901. function normalize$1(a) {
  47902. if (!(a instanceof Array)) {
  47903. a = [a, a];
  47904. }
  47905. return a;
  47906. }
  47907. var edgeVisual = function (ecModel) {
  47908. ecModel.eachSeriesByType('graph', function (seriesModel) {
  47909. var graph = seriesModel.getGraph();
  47910. var edgeData = seriesModel.getEdgeData();
  47911. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  47912. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  47913. var colorQuery = 'lineStyle.color'.split('.');
  47914. var opacityQuery = 'lineStyle.opacity'.split('.');
  47915. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  47916. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  47917. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  47918. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  47919. edgeData.setVisual('color', seriesModel.get(colorQuery));
  47920. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  47921. edgeData.each(function (idx) {
  47922. var itemModel = edgeData.getItemModel(idx);
  47923. var edge = graph.getEdgeByIndex(idx);
  47924. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  47925. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  47926. // Edge visual must after node visual
  47927. var color = itemModel.get(colorQuery);
  47928. var opacity = itemModel.get(opacityQuery);
  47929. switch (color) {
  47930. case 'source':
  47931. color = edge.node1.getVisual('color');
  47932. break;
  47933. case 'target':
  47934. color = edge.node2.getVisual('color');
  47935. break;
  47936. }
  47937. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  47938. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  47939. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  47940. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  47941. edge.setVisual('color', color);
  47942. edge.setVisual('opacity', opacity);
  47943. });
  47944. });
  47945. };
  47946. /*
  47947. * Licensed to the Apache Software Foundation (ASF) under one
  47948. * or more contributor license agreements. See the NOTICE file
  47949. * distributed with this work for additional information
  47950. * regarding copyright ownership. The ASF licenses this file
  47951. * to you under the Apache License, Version 2.0 (the
  47952. * "License"); you may not use this file except in compliance
  47953. * with the License. You may obtain a copy of the License at
  47954. *
  47955. * http://www.apache.org/licenses/LICENSE-2.0
  47956. *
  47957. * Unless required by applicable law or agreed to in writing,
  47958. * software distributed under the License is distributed on an
  47959. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47960. * KIND, either express or implied. See the License for the
  47961. * specific language governing permissions and limitations
  47962. * under the License.
  47963. */
  47964. function simpleLayout$1(seriesModel) {
  47965. var coordSys = seriesModel.coordinateSystem;
  47966. if (coordSys && coordSys.type !== 'view') {
  47967. return;
  47968. }
  47969. var graph = seriesModel.getGraph();
  47970. graph.eachNode(function (node) {
  47971. var model = node.getModel();
  47972. node.setLayout([+model.get('x'), +model.get('y')]);
  47973. });
  47974. simpleLayoutEdge(graph);
  47975. }
  47976. function simpleLayoutEdge(graph) {
  47977. graph.eachEdge(function (edge) {
  47978. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  47979. var p1 = clone$1(edge.node1.getLayout());
  47980. var p2 = clone$1(edge.node2.getLayout());
  47981. var points = [p1, p2];
  47982. if (+curveness) {
  47983. points.push([
  47984. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  47985. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  47986. ]);
  47987. }
  47988. edge.setLayout(points);
  47989. });
  47990. }
  47991. /*
  47992. * Licensed to the Apache Software Foundation (ASF) under one
  47993. * or more contributor license agreements. See the NOTICE file
  47994. * distributed with this work for additional information
  47995. * regarding copyright ownership. The ASF licenses this file
  47996. * to you under the Apache License, Version 2.0 (the
  47997. * "License"); you may not use this file except in compliance
  47998. * with the License. You may obtain a copy of the License at
  47999. *
  48000. * http://www.apache.org/licenses/LICENSE-2.0
  48001. *
  48002. * Unless required by applicable law or agreed to in writing,
  48003. * software distributed under the License is distributed on an
  48004. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48005. * KIND, either express or implied. See the License for the
  48006. * specific language governing permissions and limitations
  48007. * under the License.
  48008. */
  48009. var simpleLayout = function (ecModel, api) {
  48010. ecModel.eachSeriesByType('graph', function (seriesModel) {
  48011. var layout = seriesModel.get('layout');
  48012. var coordSys = seriesModel.coordinateSystem;
  48013. if (coordSys && coordSys.type !== 'view') {
  48014. var data = seriesModel.getData();
  48015. var dimensions = [];
  48016. each$1(coordSys.dimensions, function (coordDim) {
  48017. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  48018. });
  48019. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  48020. var value = [];
  48021. var hasValue = false;
  48022. for (var i = 0; i < dimensions.length; i++) {
  48023. var val = data.get(dimensions[i], dataIndex);
  48024. if (!isNaN(val)) {
  48025. hasValue = true;
  48026. }
  48027. value.push(val);
  48028. }
  48029. if (hasValue) {
  48030. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  48031. }
  48032. else {
  48033. // Also {Array.<number>}, not undefined to avoid if...else... statement
  48034. data.setItemLayout(dataIndex, [NaN, NaN]);
  48035. }
  48036. }
  48037. simpleLayoutEdge(data.graph);
  48038. }
  48039. else if (!layout || layout === 'none') {
  48040. simpleLayout$1(seriesModel);
  48041. }
  48042. });
  48043. };
  48044. /*
  48045. * Licensed to the Apache Software Foundation (ASF) under one
  48046. * or more contributor license agreements. See the NOTICE file
  48047. * distributed with this work for additional information
  48048. * regarding copyright ownership. The ASF licenses this file
  48049. * to you under the Apache License, Version 2.0 (the
  48050. * "License"); you may not use this file except in compliance
  48051. * with the License. You may obtain a copy of the License at
  48052. *
  48053. * http://www.apache.org/licenses/LICENSE-2.0
  48054. *
  48055. * Unless required by applicable law or agreed to in writing,
  48056. * software distributed under the License is distributed on an
  48057. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48058. * KIND, either express or implied. See the License for the
  48059. * specific language governing permissions and limitations
  48060. * under the License.
  48061. */
  48062. function circularLayout$1(seriesModel) {
  48063. var coordSys = seriesModel.coordinateSystem;
  48064. if (coordSys && coordSys.type !== 'view') {
  48065. return;
  48066. }
  48067. var rect = coordSys.getBoundingRect();
  48068. var nodeData = seriesModel.getData();
  48069. var graph = nodeData.graph;
  48070. var angle = 0;
  48071. var sum = nodeData.getSum('value');
  48072. var unitAngle = Math.PI * 2 / (sum || nodeData.count());
  48073. var cx = rect.width / 2 + rect.x;
  48074. var cy = rect.height / 2 + rect.y;
  48075. var r = Math.min(rect.width, rect.height) / 2;
  48076. graph.eachNode(function (node) {
  48077. var value = node.getValue('value');
  48078. angle += unitAngle * (sum ? value : 1) / 2;
  48079. node.setLayout([
  48080. r * Math.cos(angle) + cx,
  48081. r * Math.sin(angle) + cy
  48082. ]);
  48083. angle += unitAngle * (sum ? value : 1) / 2;
  48084. });
  48085. nodeData.setLayout({
  48086. cx: cx,
  48087. cy: cy
  48088. });
  48089. graph.eachEdge(function (edge) {
  48090. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  48091. var p1 = clone$1(edge.node1.getLayout());
  48092. var p2 = clone$1(edge.node2.getLayout());
  48093. var cp1;
  48094. var x12 = (p1[0] + p2[0]) / 2;
  48095. var y12 = (p1[1] + p2[1]) / 2;
  48096. if (+curveness) {
  48097. curveness *= 3;
  48098. cp1 = [
  48099. cx * curveness + x12 * (1 - curveness),
  48100. cy * curveness + y12 * (1 - curveness)
  48101. ];
  48102. }
  48103. edge.setLayout([p1, p2, cp1]);
  48104. });
  48105. }
  48106. /*
  48107. * Licensed to the Apache Software Foundation (ASF) under one
  48108. * or more contributor license agreements. See the NOTICE file
  48109. * distributed with this work for additional information
  48110. * regarding copyright ownership. The ASF licenses this file
  48111. * to you under the Apache License, Version 2.0 (the
  48112. * "License"); you may not use this file except in compliance
  48113. * with the License. You may obtain a copy of the License at
  48114. *
  48115. * http://www.apache.org/licenses/LICENSE-2.0
  48116. *
  48117. * Unless required by applicable law or agreed to in writing,
  48118. * software distributed under the License is distributed on an
  48119. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48120. * KIND, either express or implied. See the License for the
  48121. * specific language governing permissions and limitations
  48122. * under the License.
  48123. */
  48124. var circularLayout = function (ecModel) {
  48125. ecModel.eachSeriesByType('graph', function (seriesModel) {
  48126. if (seriesModel.get('layout') === 'circular') {
  48127. circularLayout$1(seriesModel);
  48128. }
  48129. });
  48130. };
  48131. /*
  48132. * Licensed to the Apache Software Foundation (ASF) under one
  48133. * or more contributor license agreements. See the NOTICE file
  48134. * distributed with this work for additional information
  48135. * regarding copyright ownership. The ASF licenses this file
  48136. * to you under the Apache License, Version 2.0 (the
  48137. * "License"); you may not use this file except in compliance
  48138. * with the License. You may obtain a copy of the License at
  48139. *
  48140. * http://www.apache.org/licenses/LICENSE-2.0
  48141. *
  48142. * Unless required by applicable law or agreed to in writing,
  48143. * software distributed under the License is distributed on an
  48144. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48145. * KIND, either express or implied. See the License for the
  48146. * specific language governing permissions and limitations
  48147. * under the License.
  48148. */
  48149. /*
  48150. * A third-party license is embeded for some of the code in this file:
  48151. * Some formulas were originally copied from "d3.js" with some
  48152. * modifications made for this project.
  48153. * (See more details in the comment of the method "step" below.)
  48154. * The use of the source code of this file is also subject to the terms
  48155. * and consitions of the license of "d3.js" (BSD-3Clause, see
  48156. * </licenses/LICENSE-d3>).
  48157. */
  48158. var scaleAndAdd$2 = scaleAndAdd;
  48159. // function adjacentNode(n, e) {
  48160. // return e.n1 === n ? e.n2 : e.n1;
  48161. // }
  48162. function forceLayout$1(nodes, edges, opts) {
  48163. var rect = opts.rect;
  48164. var width = rect.width;
  48165. var height = rect.height;
  48166. var center = [rect.x + width / 2, rect.y + height / 2];
  48167. // var scale = opts.scale || 1;
  48168. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  48169. // for (var i = 0; i < edges.length; i++) {
  48170. // var e = edges[i];
  48171. // var n1 = e.n1;
  48172. // var n2 = e.n2;
  48173. // n1.edges = n1.edges || [];
  48174. // n2.edges = n2.edges || [];
  48175. // n1.edges.push(e);
  48176. // n2.edges.push(e);
  48177. // }
  48178. // Init position
  48179. for (var i = 0; i < nodes.length; i++) {
  48180. var n = nodes[i];
  48181. if (!n.p) {
  48182. n.p = create(
  48183. width * (Math.random() - 0.5) + center[0],
  48184. height * (Math.random() - 0.5) + center[1]
  48185. );
  48186. }
  48187. n.pp = clone$1(n.p);
  48188. n.edges = null;
  48189. }
  48190. // Formula in 'Graph Drawing by Force-directed Placement'
  48191. // var k = scale * Math.sqrt(width * height / nodes.length);
  48192. // var k2 = k * k;
  48193. var friction = 0.6;
  48194. return {
  48195. warmUp: function () {
  48196. friction = 0.5;
  48197. },
  48198. setFixed: function (idx) {
  48199. nodes[idx].fixed = true;
  48200. },
  48201. setUnfixed: function (idx) {
  48202. nodes[idx].fixed = false;
  48203. },
  48204. /**
  48205. * Some formulas were originally copied from "d3.js"
  48206. * https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/layout/force.js
  48207. * with some modifications made for this project.
  48208. * See the license statement at the head of this file.
  48209. */
  48210. step: function (cb) {
  48211. var v12 = [];
  48212. var nLen = nodes.length;
  48213. for (var i = 0; i < edges.length; i++) {
  48214. var e = edges[i];
  48215. var n1 = e.n1;
  48216. var n2 = e.n2;
  48217. sub(v12, n2.p, n1.p);
  48218. var d = len(v12) - e.d;
  48219. var w = n2.w / (n1.w + n2.w);
  48220. if (isNaN(w)) {
  48221. w = 0;
  48222. }
  48223. normalize(v12, v12);
  48224. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  48225. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  48226. }
  48227. // Gravity
  48228. for (var i = 0; i < nLen; i++) {
  48229. var n = nodes[i];
  48230. if (!n.fixed) {
  48231. sub(v12, center, n.p);
  48232. // var d = vec2.len(v12);
  48233. // vec2.scale(v12, v12, 1 / d);
  48234. // var gravityFactor = gravity;
  48235. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  48236. }
  48237. }
  48238. // Repulsive
  48239. // PENDING
  48240. for (var i = 0; i < nLen; i++) {
  48241. var n1 = nodes[i];
  48242. for (var j = i + 1; j < nLen; j++) {
  48243. var n2 = nodes[j];
  48244. sub(v12, n2.p, n1.p);
  48245. var d = len(v12);
  48246. if (d === 0) {
  48247. // Random repulse
  48248. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  48249. d = 1;
  48250. }
  48251. var repFact = (n1.rep + n2.rep) / d / d;
  48252. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  48253. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  48254. }
  48255. }
  48256. var v = [];
  48257. for (var i = 0; i < nLen; i++) {
  48258. var n = nodes[i];
  48259. if (!n.fixed) {
  48260. sub(v, n.p, n.pp);
  48261. scaleAndAdd$2(n.p, n.p, v, friction);
  48262. copy(n.pp, n.p);
  48263. }
  48264. }
  48265. friction = friction * 0.992;
  48266. cb && cb(nodes, edges, friction < 0.01);
  48267. }
  48268. };
  48269. }
  48270. /*
  48271. * Licensed to the Apache Software Foundation (ASF) under one
  48272. * or more contributor license agreements. See the NOTICE file
  48273. * distributed with this work for additional information
  48274. * regarding copyright ownership. The ASF licenses this file
  48275. * to you under the Apache License, Version 2.0 (the
  48276. * "License"); you may not use this file except in compliance
  48277. * with the License. You may obtain a copy of the License at
  48278. *
  48279. * http://www.apache.org/licenses/LICENSE-2.0
  48280. *
  48281. * Unless required by applicable law or agreed to in writing,
  48282. * software distributed under the License is distributed on an
  48283. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48284. * KIND, either express or implied. See the License for the
  48285. * specific language governing permissions and limitations
  48286. * under the License.
  48287. */
  48288. var forceLayout = function (ecModel) {
  48289. ecModel.eachSeriesByType('graph', function (graphSeries) {
  48290. var coordSys = graphSeries.coordinateSystem;
  48291. if (coordSys && coordSys.type !== 'view') {
  48292. return;
  48293. }
  48294. if (graphSeries.get('layout') === 'force') {
  48295. var preservedPoints = graphSeries.preservedPoints || {};
  48296. var graph = graphSeries.getGraph();
  48297. var nodeData = graph.data;
  48298. var edgeData = graph.edgeData;
  48299. var forceModel = graphSeries.getModel('force');
  48300. var initLayout = forceModel.get('initLayout');
  48301. if (graphSeries.preservedPoints) {
  48302. nodeData.each(function (idx) {
  48303. var id = nodeData.getId(idx);
  48304. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  48305. });
  48306. }
  48307. else if (!initLayout || initLayout === 'none') {
  48308. simpleLayout$1(graphSeries);
  48309. }
  48310. else if (initLayout === 'circular') {
  48311. circularLayout$1(graphSeries);
  48312. }
  48313. var nodeDataExtent = nodeData.getDataExtent('value');
  48314. var edgeDataExtent = edgeData.getDataExtent('value');
  48315. // var edgeDataExtent = edgeData.getDataExtent('value');
  48316. var repulsion = forceModel.get('repulsion');
  48317. var edgeLength = forceModel.get('edgeLength');
  48318. if (!isArray(repulsion)) {
  48319. repulsion = [repulsion, repulsion];
  48320. }
  48321. if (!isArray(edgeLength)) {
  48322. edgeLength = [edgeLength, edgeLength];
  48323. }
  48324. // Larger value has smaller length
  48325. edgeLength = [edgeLength[1], edgeLength[0]];
  48326. var nodes = nodeData.mapArray('value', function (value, idx) {
  48327. var point = nodeData.getItemLayout(idx);
  48328. var rep = linearMap(value, nodeDataExtent, repulsion);
  48329. if (isNaN(rep)) {
  48330. rep = (repulsion[0] + repulsion[1]) / 2;
  48331. }
  48332. return {
  48333. w: rep,
  48334. rep: rep,
  48335. fixed: nodeData.getItemModel(idx).get('fixed'),
  48336. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  48337. };
  48338. });
  48339. var edges = edgeData.mapArray('value', function (value, idx) {
  48340. var edge = graph.getEdgeByIndex(idx);
  48341. var d = linearMap(value, edgeDataExtent, edgeLength);
  48342. if (isNaN(d)) {
  48343. d = (edgeLength[0] + edgeLength[1]) / 2;
  48344. }
  48345. return {
  48346. n1: nodes[edge.node1.dataIndex],
  48347. n2: nodes[edge.node2.dataIndex],
  48348. d: d,
  48349. curveness: edge.getModel().get('lineStyle.curveness') || 0
  48350. };
  48351. });
  48352. var coordSys = graphSeries.coordinateSystem;
  48353. var rect = coordSys.getBoundingRect();
  48354. var forceInstance = forceLayout$1(nodes, edges, {
  48355. rect: rect,
  48356. gravity: forceModel.get('gravity')
  48357. });
  48358. var oldStep = forceInstance.step;
  48359. forceInstance.step = function (cb) {
  48360. for (var i = 0, l = nodes.length; i < l; i++) {
  48361. if (nodes[i].fixed) {
  48362. // Write back to layout instance
  48363. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  48364. }
  48365. }
  48366. oldStep(function (nodes, edges, stopped) {
  48367. for (var i = 0, l = nodes.length; i < l; i++) {
  48368. if (!nodes[i].fixed) {
  48369. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  48370. }
  48371. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  48372. }
  48373. for (var i = 0, l = edges.length; i < l; i++) {
  48374. var e = edges[i];
  48375. var edge = graph.getEdgeByIndex(i);
  48376. var p1 = e.n1.p;
  48377. var p2 = e.n2.p;
  48378. var points = edge.getLayout();
  48379. points = points ? points.slice() : [];
  48380. points[0] = points[0] || [];
  48381. points[1] = points[1] || [];
  48382. copy(points[0], p1);
  48383. copy(points[1], p2);
  48384. if (+e.curveness) {
  48385. points[2] = [
  48386. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  48387. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  48388. ];
  48389. }
  48390. edge.setLayout(points);
  48391. }
  48392. // Update layout
  48393. cb && cb(stopped);
  48394. });
  48395. };
  48396. graphSeries.forceLayout = forceInstance;
  48397. graphSeries.preservedPoints = preservedPoints;
  48398. // Step to get the layout
  48399. forceInstance.step();
  48400. }
  48401. else {
  48402. // Remove prev injected forceLayout instance
  48403. graphSeries.forceLayout = null;
  48404. }
  48405. });
  48406. };
  48407. /*
  48408. * Licensed to the Apache Software Foundation (ASF) under one
  48409. * or more contributor license agreements. See the NOTICE file
  48410. * distributed with this work for additional information
  48411. * regarding copyright ownership. The ASF licenses this file
  48412. * to you under the Apache License, Version 2.0 (the
  48413. * "License"); you may not use this file except in compliance
  48414. * with the License. You may obtain a copy of the License at
  48415. *
  48416. * http://www.apache.org/licenses/LICENSE-2.0
  48417. *
  48418. * Unless required by applicable law or agreed to in writing,
  48419. * software distributed under the License is distributed on an
  48420. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48421. * KIND, either express or implied. See the License for the
  48422. * specific language governing permissions and limitations
  48423. * under the License.
  48424. */
  48425. // FIXME Where to create the simple view coordinate system
  48426. function getViewRect$1(seriesModel, api, aspect) {
  48427. var option = seriesModel.getBoxLayoutParams();
  48428. option.aspect = aspect;
  48429. return getLayoutRect(option, {
  48430. width: api.getWidth(),
  48431. height: api.getHeight()
  48432. });
  48433. }
  48434. var createView = function (ecModel, api) {
  48435. var viewList = [];
  48436. ecModel.eachSeriesByType('graph', function (seriesModel) {
  48437. var coordSysType = seriesModel.get('coordinateSystem');
  48438. if (!coordSysType || coordSysType === 'view') {
  48439. var data = seriesModel.getData();
  48440. var positions = data.mapArray(function (idx) {
  48441. var itemModel = data.getItemModel(idx);
  48442. return [+itemModel.get('x'), +itemModel.get('y')];
  48443. });
  48444. var min = [];
  48445. var max = [];
  48446. fromPoints(positions, min, max);
  48447. // If width or height is 0
  48448. if (max[0] - min[0] === 0) {
  48449. max[0] += 1;
  48450. min[0] -= 1;
  48451. }
  48452. if (max[1] - min[1] === 0) {
  48453. max[1] += 1;
  48454. min[1] -= 1;
  48455. }
  48456. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  48457. // FIXME If get view rect after data processed?
  48458. var viewRect = getViewRect$1(seriesModel, api, aspect);
  48459. // Position may be NaN, use view rect instead
  48460. if (isNaN(aspect)) {
  48461. min = [viewRect.x, viewRect.y];
  48462. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  48463. }
  48464. var bbWidth = max[0] - min[0];
  48465. var bbHeight = max[1] - min[1];
  48466. var viewWidth = viewRect.width;
  48467. var viewHeight = viewRect.height;
  48468. var viewCoordSys = seriesModel.coordinateSystem = new View();
  48469. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  48470. viewCoordSys.setBoundingRect(
  48471. min[0], min[1], bbWidth, bbHeight
  48472. );
  48473. viewCoordSys.setViewRect(
  48474. viewRect.x, viewRect.y, viewWidth, viewHeight
  48475. );
  48476. // Update roam info
  48477. viewCoordSys.setCenter(seriesModel.get('center'));
  48478. viewCoordSys.setZoom(seriesModel.get('zoom'));
  48479. viewList.push(viewCoordSys);
  48480. }
  48481. });
  48482. return viewList;
  48483. };
  48484. /*
  48485. * Licensed to the Apache Software Foundation (ASF) under one
  48486. * or more contributor license agreements. See the NOTICE file
  48487. * distributed with this work for additional information
  48488. * regarding copyright ownership. The ASF licenses this file
  48489. * to you under the Apache License, Version 2.0 (the
  48490. * "License"); you may not use this file except in compliance
  48491. * with the License. You may obtain a copy of the License at
  48492. *
  48493. * http://www.apache.org/licenses/LICENSE-2.0
  48494. *
  48495. * Unless required by applicable law or agreed to in writing,
  48496. * software distributed under the License is distributed on an
  48497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48498. * KIND, either express or implied. See the License for the
  48499. * specific language governing permissions and limitations
  48500. * under the License.
  48501. */
  48502. registerProcessor(categoryFilter);
  48503. registerVisual(visualSymbol('graph', 'circle', null));
  48504. registerVisual(categoryVisual);
  48505. registerVisual(edgeVisual);
  48506. registerLayout(simpleLayout);
  48507. registerLayout(circularLayout);
  48508. registerLayout(forceLayout);
  48509. // Graph view coordinate system
  48510. registerCoordinateSystem('graphView', {
  48511. create: createView
  48512. });
  48513. /*
  48514. * Licensed to the Apache Software Foundation (ASF) under one
  48515. * or more contributor license agreements. See the NOTICE file
  48516. * distributed with this work for additional information
  48517. * regarding copyright ownership. The ASF licenses this file
  48518. * to you under the Apache License, Version 2.0 (the
  48519. * "License"); you may not use this file except in compliance
  48520. * with the License. You may obtain a copy of the License at
  48521. *
  48522. * http://www.apache.org/licenses/LICENSE-2.0
  48523. *
  48524. * Unless required by applicable law or agreed to in writing,
  48525. * software distributed under the License is distributed on an
  48526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48527. * KIND, either express or implied. See the License for the
  48528. * specific language governing permissions and limitations
  48529. * under the License.
  48530. */
  48531. var GaugeSeries = SeriesModel.extend({
  48532. type: 'series.gauge',
  48533. getInitialData: function (option, ecModel) {
  48534. var dataOpt = option.data || [];
  48535. if (!isArray(dataOpt)) {
  48536. dataOpt = [dataOpt];
  48537. }
  48538. option.data = dataOpt;
  48539. return createListSimply(this, ['value']);
  48540. },
  48541. defaultOption: {
  48542. zlevel: 0,
  48543. z: 2,
  48544. // 默认全局居中
  48545. center: ['50%', '50%'],
  48546. legendHoverLink: true,
  48547. radius: '75%',
  48548. startAngle: 225,
  48549. endAngle: -45,
  48550. clockwise: true,
  48551. // 最小值
  48552. min: 0,
  48553. // 最大值
  48554. max: 100,
  48555. // 分割段数,默认为10
  48556. splitNumber: 10,
  48557. // 坐标轴线
  48558. axisLine: {
  48559. // 默认显示,属性show控制显示与否
  48560. show: true,
  48561. lineStyle: { // 属性lineStyle控制线条样式
  48562. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  48563. width: 30
  48564. }
  48565. },
  48566. // 分隔线
  48567. splitLine: {
  48568. // 默认显示,属性show控制显示与否
  48569. show: true,
  48570. // 属性length控制线长
  48571. length: 30,
  48572. // 属性lineStyle(详见lineStyle)控制线条样式
  48573. lineStyle: {
  48574. color: '#eee',
  48575. width: 2,
  48576. type: 'solid'
  48577. }
  48578. },
  48579. // 坐标轴小标记
  48580. axisTick: {
  48581. // 属性show控制显示与否,默认不显示
  48582. show: true,
  48583. // 每份split细分多少段
  48584. splitNumber: 5,
  48585. // 属性length控制线长
  48586. length: 8,
  48587. // 属性lineStyle控制线条样式
  48588. lineStyle: {
  48589. color: '#eee',
  48590. width: 1,
  48591. type: 'solid'
  48592. }
  48593. },
  48594. axisLabel: {
  48595. show: true,
  48596. distance: 5,
  48597. // formatter: null,
  48598. color: 'auto'
  48599. },
  48600. pointer: {
  48601. show: true,
  48602. length: '80%',
  48603. width: 8
  48604. },
  48605. itemStyle: {
  48606. color: 'auto'
  48607. },
  48608. title: {
  48609. show: true,
  48610. // x, y,单位px
  48611. offsetCenter: [0, '-40%'],
  48612. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  48613. color: '#333',
  48614. fontSize: 15
  48615. },
  48616. detail: {
  48617. show: true,
  48618. backgroundColor: 'rgba(0,0,0,0)',
  48619. borderWidth: 0,
  48620. borderColor: '#ccc',
  48621. width: 100,
  48622. height: null, // self-adaption
  48623. padding: [5, 10],
  48624. // x, y,单位px
  48625. offsetCenter: [0, '40%'],
  48626. // formatter: null,
  48627. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  48628. color: 'auto',
  48629. fontSize: 30
  48630. }
  48631. }
  48632. });
  48633. /*
  48634. * Licensed to the Apache Software Foundation (ASF) under one
  48635. * or more contributor license agreements. See the NOTICE file
  48636. * distributed with this work for additional information
  48637. * regarding copyright ownership. The ASF licenses this file
  48638. * to you under the Apache License, Version 2.0 (the
  48639. * "License"); you may not use this file except in compliance
  48640. * with the License. You may obtain a copy of the License at
  48641. *
  48642. * http://www.apache.org/licenses/LICENSE-2.0
  48643. *
  48644. * Unless required by applicable law or agreed to in writing,
  48645. * software distributed under the License is distributed on an
  48646. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48647. * KIND, either express or implied. See the License for the
  48648. * specific language governing permissions and limitations
  48649. * under the License.
  48650. */
  48651. var PointerPath = Path.extend({
  48652. type: 'echartsGaugePointer',
  48653. shape: {
  48654. angle: 0,
  48655. width: 10,
  48656. r: 10,
  48657. x: 0,
  48658. y: 0
  48659. },
  48660. buildPath: function (ctx, shape) {
  48661. var mathCos = Math.cos;
  48662. var mathSin = Math.sin;
  48663. var r = shape.r;
  48664. var width = shape.width;
  48665. var angle = shape.angle;
  48666. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  48667. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  48668. angle = shape.angle - Math.PI / 2;
  48669. ctx.moveTo(x, y);
  48670. ctx.lineTo(
  48671. shape.x + mathCos(angle) * width,
  48672. shape.y + mathSin(angle) * width
  48673. );
  48674. ctx.lineTo(
  48675. shape.x + mathCos(shape.angle) * r,
  48676. shape.y + mathSin(shape.angle) * r
  48677. );
  48678. ctx.lineTo(
  48679. shape.x - mathCos(angle) * width,
  48680. shape.y - mathSin(angle) * width
  48681. );
  48682. ctx.lineTo(x, y);
  48683. return;
  48684. }
  48685. });
  48686. /*
  48687. * Licensed to the Apache Software Foundation (ASF) under one
  48688. * or more contributor license agreements. See the NOTICE file
  48689. * distributed with this work for additional information
  48690. * regarding copyright ownership. The ASF licenses this file
  48691. * to you under the Apache License, Version 2.0 (the
  48692. * "License"); you may not use this file except in compliance
  48693. * with the License. You may obtain a copy of the License at
  48694. *
  48695. * http://www.apache.org/licenses/LICENSE-2.0
  48696. *
  48697. * Unless required by applicable law or agreed to in writing,
  48698. * software distributed under the License is distributed on an
  48699. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48700. * KIND, either express or implied. See the License for the
  48701. * specific language governing permissions and limitations
  48702. * under the License.
  48703. */
  48704. function parsePosition(seriesModel, api) {
  48705. var center = seriesModel.get('center');
  48706. var width = api.getWidth();
  48707. var height = api.getHeight();
  48708. var size = Math.min(width, height);
  48709. var cx = parsePercent$1(center[0], api.getWidth());
  48710. var cy = parsePercent$1(center[1], api.getHeight());
  48711. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  48712. return {
  48713. cx: cx,
  48714. cy: cy,
  48715. r: r
  48716. };
  48717. }
  48718. function formatLabel(label, labelFormatter) {
  48719. if (labelFormatter) {
  48720. if (typeof labelFormatter === 'string') {
  48721. label = labelFormatter.replace('{value}', label != null ? label : '');
  48722. }
  48723. else if (typeof labelFormatter === 'function') {
  48724. label = labelFormatter(label);
  48725. }
  48726. }
  48727. return label;
  48728. }
  48729. var PI2$5 = Math.PI * 2;
  48730. var GaugeView = Chart.extend({
  48731. type: 'gauge',
  48732. render: function (seriesModel, ecModel, api) {
  48733. this.group.removeAll();
  48734. var colorList = seriesModel.get('axisLine.lineStyle.color');
  48735. var posInfo = parsePosition(seriesModel, api);
  48736. this._renderMain(
  48737. seriesModel, ecModel, api, colorList, posInfo
  48738. );
  48739. },
  48740. dispose: function () {},
  48741. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  48742. var group = this.group;
  48743. var axisLineModel = seriesModel.getModel('axisLine');
  48744. var lineStyleModel = axisLineModel.getModel('lineStyle');
  48745. var clockwise = seriesModel.get('clockwise');
  48746. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  48747. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  48748. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  48749. var prevEndAngle = startAngle;
  48750. var axisLineWidth = lineStyleModel.get('width');
  48751. for (var i = 0; i < colorList.length; i++) {
  48752. // Clamp
  48753. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  48754. var endAngle = startAngle + angleRangeSpan * percent;
  48755. var sector = new Sector({
  48756. shape: {
  48757. startAngle: prevEndAngle,
  48758. endAngle: endAngle,
  48759. cx: posInfo.cx,
  48760. cy: posInfo.cy,
  48761. clockwise: clockwise,
  48762. r0: posInfo.r - axisLineWidth,
  48763. r: posInfo.r
  48764. },
  48765. silent: true
  48766. });
  48767. sector.setStyle({
  48768. fill: colorList[i][1]
  48769. });
  48770. sector.setStyle(lineStyleModel.getLineStyle(
  48771. // Because we use sector to simulate arc
  48772. // so the properties for stroking are useless
  48773. ['color', 'borderWidth', 'borderColor']
  48774. ));
  48775. group.add(sector);
  48776. prevEndAngle = endAngle;
  48777. }
  48778. var getColor = function (percent) {
  48779. // Less than 0
  48780. if (percent <= 0) {
  48781. return colorList[0][1];
  48782. }
  48783. for (var i = 0; i < colorList.length; i++) {
  48784. if (colorList[i][0] >= percent
  48785. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  48786. ) {
  48787. return colorList[i][1];
  48788. }
  48789. }
  48790. // More than 1
  48791. return colorList[i - 1][1];
  48792. };
  48793. if (!clockwise) {
  48794. var tmp = startAngle;
  48795. startAngle = endAngle;
  48796. endAngle = tmp;
  48797. }
  48798. this._renderTicks(
  48799. seriesModel, ecModel, api, getColor, posInfo,
  48800. startAngle, endAngle, clockwise
  48801. );
  48802. this._renderPointer(
  48803. seriesModel, ecModel, api, getColor, posInfo,
  48804. startAngle, endAngle, clockwise
  48805. );
  48806. this._renderTitle(
  48807. seriesModel, ecModel, api, getColor, posInfo
  48808. );
  48809. this._renderDetail(
  48810. seriesModel, ecModel, api, getColor, posInfo
  48811. );
  48812. },
  48813. _renderTicks: function (
  48814. seriesModel, ecModel, api, getColor, posInfo,
  48815. startAngle, endAngle, clockwise
  48816. ) {
  48817. var group = this.group;
  48818. var cx = posInfo.cx;
  48819. var cy = posInfo.cy;
  48820. var r = posInfo.r;
  48821. var minVal = +seriesModel.get('min');
  48822. var maxVal = +seriesModel.get('max');
  48823. var splitLineModel = seriesModel.getModel('splitLine');
  48824. var tickModel = seriesModel.getModel('axisTick');
  48825. var labelModel = seriesModel.getModel('axisLabel');
  48826. var splitNumber = seriesModel.get('splitNumber');
  48827. var subSplitNumber = tickModel.get('splitNumber');
  48828. var splitLineLen = parsePercent$1(
  48829. splitLineModel.get('length'), r
  48830. );
  48831. var tickLen = parsePercent$1(
  48832. tickModel.get('length'), r
  48833. );
  48834. var angle = startAngle;
  48835. var step = (endAngle - startAngle) / splitNumber;
  48836. var subStep = step / subSplitNumber;
  48837. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  48838. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  48839. for (var i = 0; i <= splitNumber; i++) {
  48840. var unitX = Math.cos(angle);
  48841. var unitY = Math.sin(angle);
  48842. // Split line
  48843. if (splitLineModel.get('show')) {
  48844. var splitLine = new Line({
  48845. shape: {
  48846. x1: unitX * r + cx,
  48847. y1: unitY * r + cy,
  48848. x2: unitX * (r - splitLineLen) + cx,
  48849. y2: unitY * (r - splitLineLen) + cy
  48850. },
  48851. style: splitLineStyle,
  48852. silent: true
  48853. });
  48854. if (splitLineStyle.stroke === 'auto') {
  48855. splitLine.setStyle({
  48856. stroke: getColor(i / splitNumber)
  48857. });
  48858. }
  48859. group.add(splitLine);
  48860. }
  48861. // Label
  48862. if (labelModel.get('show')) {
  48863. var label = formatLabel(
  48864. round$2(i / splitNumber * (maxVal - minVal) + minVal),
  48865. labelModel.get('formatter')
  48866. );
  48867. var distance = labelModel.get('distance');
  48868. var autoColor = getColor(i / splitNumber);
  48869. group.add(new Text({
  48870. style: setTextStyle({}, labelModel, {
  48871. text: label,
  48872. x: unitX * (r - splitLineLen - distance) + cx,
  48873. y: unitY * (r - splitLineLen - distance) + cy,
  48874. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  48875. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  48876. }, {autoColor: autoColor}),
  48877. silent: true
  48878. }));
  48879. }
  48880. // Axis tick
  48881. if (tickModel.get('show') && i !== splitNumber) {
  48882. for (var j = 0; j <= subSplitNumber; j++) {
  48883. var unitX = Math.cos(angle);
  48884. var unitY = Math.sin(angle);
  48885. var tickLine = new Line({
  48886. shape: {
  48887. x1: unitX * r + cx,
  48888. y1: unitY * r + cy,
  48889. x2: unitX * (r - tickLen) + cx,
  48890. y2: unitY * (r - tickLen) + cy
  48891. },
  48892. silent: true,
  48893. style: tickLineStyle
  48894. });
  48895. if (tickLineStyle.stroke === 'auto') {
  48896. tickLine.setStyle({
  48897. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  48898. });
  48899. }
  48900. group.add(tickLine);
  48901. angle += subStep;
  48902. }
  48903. angle -= subStep;
  48904. }
  48905. else {
  48906. angle += step;
  48907. }
  48908. }
  48909. },
  48910. _renderPointer: function (
  48911. seriesModel, ecModel, api, getColor, posInfo,
  48912. startAngle, endAngle, clockwise
  48913. ) {
  48914. var group = this.group;
  48915. var oldData = this._data;
  48916. if (!seriesModel.get('pointer.show')) {
  48917. // Remove old element
  48918. oldData && oldData.eachItemGraphicEl(function (el) {
  48919. group.remove(el);
  48920. });
  48921. return;
  48922. }
  48923. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  48924. var angleExtent = [startAngle, endAngle];
  48925. var data = seriesModel.getData();
  48926. var valueDim = data.mapDimension('value');
  48927. data.diff(oldData)
  48928. .add(function (idx) {
  48929. var pointer = new PointerPath({
  48930. shape: {
  48931. angle: startAngle
  48932. }
  48933. });
  48934. initProps(pointer, {
  48935. shape: {
  48936. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  48937. }
  48938. }, seriesModel);
  48939. group.add(pointer);
  48940. data.setItemGraphicEl(idx, pointer);
  48941. })
  48942. .update(function (newIdx, oldIdx) {
  48943. var pointer = oldData.getItemGraphicEl(oldIdx);
  48944. updateProps(pointer, {
  48945. shape: {
  48946. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  48947. }
  48948. }, seriesModel);
  48949. group.add(pointer);
  48950. data.setItemGraphicEl(newIdx, pointer);
  48951. })
  48952. .remove(function (idx) {
  48953. var pointer = oldData.getItemGraphicEl(idx);
  48954. group.remove(pointer);
  48955. })
  48956. .execute();
  48957. data.eachItemGraphicEl(function (pointer, idx) {
  48958. var itemModel = data.getItemModel(idx);
  48959. var pointerModel = itemModel.getModel('pointer');
  48960. pointer.setShape({
  48961. x: posInfo.cx,
  48962. y: posInfo.cy,
  48963. width: parsePercent$1(
  48964. pointerModel.get('width'), posInfo.r
  48965. ),
  48966. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  48967. });
  48968. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  48969. if (pointer.style.fill === 'auto') {
  48970. pointer.setStyle('fill', getColor(
  48971. linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)
  48972. ));
  48973. }
  48974. setHoverStyle(
  48975. pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle()
  48976. );
  48977. });
  48978. this._data = data;
  48979. },
  48980. _renderTitle: function (
  48981. seriesModel, ecModel, api, getColor, posInfo
  48982. ) {
  48983. var data = seriesModel.getData();
  48984. var valueDim = data.mapDimension('value');
  48985. var titleModel = seriesModel.getModel('title');
  48986. if (titleModel.get('show')) {
  48987. var offsetCenter = titleModel.get('offsetCenter');
  48988. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  48989. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  48990. var minVal = +seriesModel.get('min');
  48991. var maxVal = +seriesModel.get('max');
  48992. var value = seriesModel.getData().get(valueDim, 0);
  48993. var autoColor = getColor(
  48994. linearMap(value, [minVal, maxVal], [0, 1], true)
  48995. );
  48996. this.group.add(new Text({
  48997. silent: true,
  48998. style: setTextStyle({}, titleModel, {
  48999. x: x,
  49000. y: y,
  49001. // FIXME First data name ?
  49002. text: data.getName(0),
  49003. textAlign: 'center',
  49004. textVerticalAlign: 'middle'
  49005. }, {autoColor: autoColor, forceRich: true})
  49006. }));
  49007. }
  49008. },
  49009. _renderDetail: function (
  49010. seriesModel, ecModel, api, getColor, posInfo
  49011. ) {
  49012. var detailModel = seriesModel.getModel('detail');
  49013. var minVal = +seriesModel.get('min');
  49014. var maxVal = +seriesModel.get('max');
  49015. if (detailModel.get('show')) {
  49016. var offsetCenter = detailModel.get('offsetCenter');
  49017. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  49018. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  49019. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  49020. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  49021. var data = seriesModel.getData();
  49022. var value = data.get(data.mapDimension('value'), 0);
  49023. var autoColor = getColor(
  49024. linearMap(value, [minVal, maxVal], [0, 1], true)
  49025. );
  49026. this.group.add(new Text({
  49027. silent: true,
  49028. style: setTextStyle({}, detailModel, {
  49029. x: x,
  49030. y: y,
  49031. text: formatLabel(
  49032. // FIXME First data name ?
  49033. value, detailModel.get('formatter')
  49034. ),
  49035. textWidth: isNaN(width) ? null : width,
  49036. textHeight: isNaN(height) ? null : height,
  49037. textAlign: 'center',
  49038. textVerticalAlign: 'middle'
  49039. }, {autoColor: autoColor, forceRich: true})
  49040. }));
  49041. }
  49042. }
  49043. });
  49044. /*
  49045. * Licensed to the Apache Software Foundation (ASF) under one
  49046. * or more contributor license agreements. See the NOTICE file
  49047. * distributed with this work for additional information
  49048. * regarding copyright ownership. The ASF licenses this file
  49049. * to you under the Apache License, Version 2.0 (the
  49050. * "License"); you may not use this file except in compliance
  49051. * with the License. You may obtain a copy of the License at
  49052. *
  49053. * http://www.apache.org/licenses/LICENSE-2.0
  49054. *
  49055. * Unless required by applicable law or agreed to in writing,
  49056. * software distributed under the License is distributed on an
  49057. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49058. * KIND, either express or implied. See the License for the
  49059. * specific language governing permissions and limitations
  49060. * under the License.
  49061. */
  49062. /*
  49063. * Licensed to the Apache Software Foundation (ASF) under one
  49064. * or more contributor license agreements. See the NOTICE file
  49065. * distributed with this work for additional information
  49066. * regarding copyright ownership. The ASF licenses this file
  49067. * to you under the Apache License, Version 2.0 (the
  49068. * "License"); you may not use this file except in compliance
  49069. * with the License. You may obtain a copy of the License at
  49070. *
  49071. * http://www.apache.org/licenses/LICENSE-2.0
  49072. *
  49073. * Unless required by applicable law or agreed to in writing,
  49074. * software distributed under the License is distributed on an
  49075. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49076. * KIND, either express or implied. See the License for the
  49077. * specific language governing permissions and limitations
  49078. * under the License.
  49079. */
  49080. var FunnelSeries = extendSeriesModel({
  49081. type: 'series.funnel',
  49082. init: function (option) {
  49083. FunnelSeries.superApply(this, 'init', arguments);
  49084. // Enable legend selection for each data item
  49085. // Use a function instead of direct access because data reference may changed
  49086. this.legendDataProvider = function () {
  49087. return this.getRawData();
  49088. };
  49089. // Extend labelLine emphasis
  49090. this._defaultLabelLine(option);
  49091. },
  49092. getInitialData: function (option, ecModel) {
  49093. return createListSimply(this, ['value']);
  49094. },
  49095. _defaultLabelLine: function (option) {
  49096. // Extend labelLine emphasis
  49097. defaultEmphasis(option, 'labelLine', ['show']);
  49098. var labelLineNormalOpt = option.labelLine;
  49099. var labelLineEmphasisOpt = option.emphasis.labelLine;
  49100. // Not show label line if `label.normal.show = false`
  49101. labelLineNormalOpt.show = labelLineNormalOpt.show
  49102. && option.label.show;
  49103. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  49104. && option.emphasis.label.show;
  49105. },
  49106. // Overwrite
  49107. getDataParams: function (dataIndex) {
  49108. var data = this.getData();
  49109. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  49110. var valueDim = data.mapDimension('value');
  49111. var sum = data.getSum(valueDim);
  49112. // Percent is 0 if sum is 0
  49113. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  49114. params.$vars.push('percent');
  49115. return params;
  49116. },
  49117. defaultOption: {
  49118. zlevel: 0, // 一级层叠
  49119. z: 2, // 二级层叠
  49120. legendHoverLink: true,
  49121. left: 80,
  49122. top: 60,
  49123. right: 80,
  49124. bottom: 60,
  49125. // width: {totalWidth} - left - right,
  49126. // height: {totalHeight} - top - bottom,
  49127. // 默认取数据最小最大值
  49128. // min: 0,
  49129. // max: 100,
  49130. minSize: '0%',
  49131. maxSize: '100%',
  49132. sort: 'descending', // 'ascending', 'descending'
  49133. gap: 0,
  49134. funnelAlign: 'center',
  49135. label: {
  49136. show: true,
  49137. position: 'outer'
  49138. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  49139. },
  49140. labelLine: {
  49141. show: true,
  49142. length: 20,
  49143. lineStyle: {
  49144. // color: 各异,
  49145. width: 1,
  49146. type: 'solid'
  49147. }
  49148. },
  49149. itemStyle: {
  49150. // color: 各异,
  49151. borderColor: '#fff',
  49152. borderWidth: 1
  49153. },
  49154. emphasis: {
  49155. label: {
  49156. show: true
  49157. }
  49158. }
  49159. }
  49160. });
  49161. /*
  49162. * Licensed to the Apache Software Foundation (ASF) under one
  49163. * or more contributor license agreements. See the NOTICE file
  49164. * distributed with this work for additional information
  49165. * regarding copyright ownership. The ASF licenses this file
  49166. * to you under the Apache License, Version 2.0 (the
  49167. * "License"); you may not use this file except in compliance
  49168. * with the License. You may obtain a copy of the License at
  49169. *
  49170. * http://www.apache.org/licenses/LICENSE-2.0
  49171. *
  49172. * Unless required by applicable law or agreed to in writing,
  49173. * software distributed under the License is distributed on an
  49174. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49175. * KIND, either express or implied. See the License for the
  49176. * specific language governing permissions and limitations
  49177. * under the License.
  49178. */
  49179. /**
  49180. * Piece of pie including Sector, Label, LabelLine
  49181. * @constructor
  49182. * @extends {module:zrender/graphic/Group}
  49183. */
  49184. function FunnelPiece(data, idx) {
  49185. Group.call(this);
  49186. var polygon = new Polygon();
  49187. var labelLine = new Polyline();
  49188. var text = new Text();
  49189. this.add(polygon);
  49190. this.add(labelLine);
  49191. this.add(text);
  49192. this.updateData(data, idx, true);
  49193. // Hover to change label and labelLine
  49194. function onEmphasis() {
  49195. labelLine.ignore = labelLine.hoverIgnore;
  49196. text.ignore = text.hoverIgnore;
  49197. }
  49198. function onNormal() {
  49199. labelLine.ignore = labelLine.normalIgnore;
  49200. text.ignore = text.normalIgnore;
  49201. }
  49202. this.on('emphasis', onEmphasis)
  49203. .on('normal', onNormal)
  49204. .on('mouseover', onEmphasis)
  49205. .on('mouseout', onNormal);
  49206. }
  49207. var funnelPieceProto = FunnelPiece.prototype;
  49208. var opacityAccessPath = ['itemStyle', 'opacity'];
  49209. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  49210. var polygon = this.childAt(0);
  49211. var seriesModel = data.hostModel;
  49212. var itemModel = data.getItemModel(idx);
  49213. var layout = data.getItemLayout(idx);
  49214. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  49215. opacity = opacity == null ? 1 : opacity;
  49216. // Reset style
  49217. polygon.useStyle({});
  49218. if (firstCreate) {
  49219. polygon.setShape({
  49220. points: layout.points
  49221. });
  49222. polygon.setStyle({opacity: 0});
  49223. initProps(polygon, {
  49224. style: {
  49225. opacity: opacity
  49226. }
  49227. }, seriesModel, idx);
  49228. }
  49229. else {
  49230. updateProps(polygon, {
  49231. style: {
  49232. opacity: opacity
  49233. },
  49234. shape: {
  49235. points: layout.points
  49236. }
  49237. }, seriesModel, idx);
  49238. }
  49239. // Update common style
  49240. var itemStyleModel = itemModel.getModel('itemStyle');
  49241. var visualColor = data.getItemVisual(idx, 'color');
  49242. polygon.setStyle(
  49243. defaults(
  49244. {
  49245. lineJoin: 'round',
  49246. fill: visualColor
  49247. },
  49248. itemStyleModel.getItemStyle(['opacity'])
  49249. )
  49250. );
  49251. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  49252. this._updateLabel(data, idx);
  49253. setHoverStyle(this);
  49254. };
  49255. funnelPieceProto._updateLabel = function (data, idx) {
  49256. var labelLine = this.childAt(1);
  49257. var labelText = this.childAt(2);
  49258. var seriesModel = data.hostModel;
  49259. var itemModel = data.getItemModel(idx);
  49260. var layout = data.getItemLayout(idx);
  49261. var labelLayout = layout.label;
  49262. var visualColor = data.getItemVisual(idx, 'color');
  49263. updateProps(labelLine, {
  49264. shape: {
  49265. points: labelLayout.linePoints || labelLayout.linePoints
  49266. }
  49267. }, seriesModel, idx);
  49268. updateProps(labelText, {
  49269. style: {
  49270. x: labelLayout.x,
  49271. y: labelLayout.y
  49272. }
  49273. }, seriesModel, idx);
  49274. labelText.attr({
  49275. rotation: labelLayout.rotation,
  49276. origin: [labelLayout.x, labelLayout.y],
  49277. z2: 10
  49278. });
  49279. var labelModel = itemModel.getModel('label');
  49280. var labelHoverModel = itemModel.getModel('emphasis.label');
  49281. var labelLineModel = itemModel.getModel('labelLine');
  49282. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  49283. var visualColor = data.getItemVisual(idx, 'color');
  49284. setLabelStyle(
  49285. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  49286. {
  49287. labelFetcher: data.hostModel,
  49288. labelDataIndex: idx,
  49289. defaultText: data.getName(idx),
  49290. autoColor: visualColor,
  49291. useInsideStyle: !!labelLayout.inside
  49292. },
  49293. {
  49294. textAlign: labelLayout.textAlign,
  49295. textVerticalAlign: labelLayout.verticalAlign
  49296. }
  49297. );
  49298. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  49299. labelText.hoverIgnore = !labelHoverModel.get('show');
  49300. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  49301. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  49302. // Default use item visual color
  49303. labelLine.setStyle({
  49304. stroke: visualColor
  49305. });
  49306. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  49307. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  49308. };
  49309. inherits(FunnelPiece, Group);
  49310. var FunnelView = Chart.extend({
  49311. type: 'funnel',
  49312. render: function (seriesModel, ecModel, api) {
  49313. var data = seriesModel.getData();
  49314. var oldData = this._data;
  49315. var group = this.group;
  49316. data.diff(oldData)
  49317. .add(function (idx) {
  49318. var funnelPiece = new FunnelPiece(data, idx);
  49319. data.setItemGraphicEl(idx, funnelPiece);
  49320. group.add(funnelPiece);
  49321. })
  49322. .update(function (newIdx, oldIdx) {
  49323. var piePiece = oldData.getItemGraphicEl(oldIdx);
  49324. piePiece.updateData(data, newIdx);
  49325. group.add(piePiece);
  49326. data.setItemGraphicEl(newIdx, piePiece);
  49327. })
  49328. .remove(function (idx) {
  49329. var piePiece = oldData.getItemGraphicEl(idx);
  49330. group.remove(piePiece);
  49331. })
  49332. .execute();
  49333. this._data = data;
  49334. },
  49335. remove: function () {
  49336. this.group.removeAll();
  49337. this._data = null;
  49338. },
  49339. dispose: function () {}
  49340. });
  49341. /*
  49342. * Licensed to the Apache Software Foundation (ASF) under one
  49343. * or more contributor license agreements. See the NOTICE file
  49344. * distributed with this work for additional information
  49345. * regarding copyright ownership. The ASF licenses this file
  49346. * to you under the Apache License, Version 2.0 (the
  49347. * "License"); you may not use this file except in compliance
  49348. * with the License. You may obtain a copy of the License at
  49349. *
  49350. * http://www.apache.org/licenses/LICENSE-2.0
  49351. *
  49352. * Unless required by applicable law or agreed to in writing,
  49353. * software distributed under the License is distributed on an
  49354. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49355. * KIND, either express or implied. See the License for the
  49356. * specific language governing permissions and limitations
  49357. * under the License.
  49358. */
  49359. function getViewRect$2(seriesModel, api) {
  49360. return getLayoutRect(
  49361. seriesModel.getBoxLayoutParams(), {
  49362. width: api.getWidth(),
  49363. height: api.getHeight()
  49364. }
  49365. );
  49366. }
  49367. function getSortedIndices(data, sort) {
  49368. var valueDim = data.mapDimension('value');
  49369. var valueArr = data.mapArray(valueDim, function (val) {
  49370. return val;
  49371. });
  49372. var indices = [];
  49373. var isAscending = sort === 'ascending';
  49374. for (var i = 0, len = data.count(); i < len; i++) {
  49375. indices[i] = i;
  49376. }
  49377. // Add custom sortable function & none sortable opetion by "options.sort"
  49378. if (typeof sort === 'function') {
  49379. indices.sort(sort);
  49380. }
  49381. else if (sort !== 'none') {
  49382. indices.sort(function (a, b) {
  49383. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  49384. });
  49385. }
  49386. return indices;
  49387. }
  49388. function labelLayout$1(data) {
  49389. data.each(function (idx) {
  49390. var itemModel = data.getItemModel(idx);
  49391. var labelModel = itemModel.getModel('label');
  49392. var labelPosition = labelModel.get('position');
  49393. var labelLineModel = itemModel.getModel('labelLine');
  49394. var layout = data.getItemLayout(idx);
  49395. var points = layout.points;
  49396. var isLabelInside = labelPosition === 'inner'
  49397. || labelPosition === 'inside' || labelPosition === 'center';
  49398. var textAlign;
  49399. var textX;
  49400. var textY;
  49401. var linePoints;
  49402. if (isLabelInside) {
  49403. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  49404. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  49405. textAlign = 'center';
  49406. linePoints = [
  49407. [textX, textY], [textX, textY]
  49408. ];
  49409. }
  49410. else {
  49411. var x1;
  49412. var y1;
  49413. var x2;
  49414. var labelLineLen = labelLineModel.get('length');
  49415. if (labelPosition === 'left') {
  49416. // Left side
  49417. x1 = (points[3][0] + points[0][0]) / 2;
  49418. y1 = (points[3][1] + points[0][1]) / 2;
  49419. x2 = x1 - labelLineLen;
  49420. textX = x2 - 5;
  49421. textAlign = 'right';
  49422. }
  49423. else {
  49424. // Right side
  49425. x1 = (points[1][0] + points[2][0]) / 2;
  49426. y1 = (points[1][1] + points[2][1]) / 2;
  49427. x2 = x1 + labelLineLen;
  49428. textX = x2 + 5;
  49429. textAlign = 'left';
  49430. }
  49431. var y2 = y1;
  49432. linePoints = [[x1, y1], [x2, y2]];
  49433. textY = y2;
  49434. }
  49435. layout.label = {
  49436. linePoints: linePoints,
  49437. x: textX,
  49438. y: textY,
  49439. verticalAlign: 'middle',
  49440. textAlign: textAlign,
  49441. inside: isLabelInside
  49442. };
  49443. });
  49444. }
  49445. var funnelLayout = function (ecModel, api, payload) {
  49446. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  49447. var data = seriesModel.getData();
  49448. var valueDim = data.mapDimension('value');
  49449. var sort = seriesModel.get('sort');
  49450. var viewRect = getViewRect$2(seriesModel, api);
  49451. var indices = getSortedIndices(data, sort);
  49452. var sizeExtent = [
  49453. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  49454. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  49455. ];
  49456. var dataExtent = data.getDataExtent(valueDim);
  49457. var min = seriesModel.get('min');
  49458. var max = seriesModel.get('max');
  49459. if (min == null) {
  49460. min = Math.min(dataExtent[0], 0);
  49461. }
  49462. if (max == null) {
  49463. max = dataExtent[1];
  49464. }
  49465. var funnelAlign = seriesModel.get('funnelAlign');
  49466. var gap = seriesModel.get('gap');
  49467. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  49468. var y = viewRect.y;
  49469. var getLinePoints = function (idx, offY) {
  49470. // End point index is data.count() and we assign it 0
  49471. var val = data.get(valueDim, idx) || 0;
  49472. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  49473. var x0;
  49474. switch (funnelAlign) {
  49475. case 'left':
  49476. x0 = viewRect.x;
  49477. break;
  49478. case 'center':
  49479. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  49480. break;
  49481. case 'right':
  49482. x0 = viewRect.x + viewRect.width - itemWidth;
  49483. break;
  49484. }
  49485. return [
  49486. [x0, offY],
  49487. [x0 + itemWidth, offY]
  49488. ];
  49489. };
  49490. if (sort === 'ascending') {
  49491. // From bottom to top
  49492. itemHeight = -itemHeight;
  49493. gap = -gap;
  49494. y += viewRect.height;
  49495. indices = indices.reverse();
  49496. }
  49497. for (var i = 0; i < indices.length; i++) {
  49498. var idx = indices[i];
  49499. var nextIdx = indices[i + 1];
  49500. var itemModel = data.getItemModel(idx);
  49501. var height = itemModel.get('itemStyle.height');
  49502. if (height == null) {
  49503. height = itemHeight;
  49504. }
  49505. else {
  49506. height = parsePercent$1(height, viewRect.height);
  49507. if (sort === 'ascending') {
  49508. height = -height;
  49509. }
  49510. }
  49511. var start = getLinePoints(idx, y);
  49512. var end = getLinePoints(nextIdx, y + height);
  49513. y += height + gap;
  49514. data.setItemLayout(idx, {
  49515. points: start.concat(end.slice().reverse())
  49516. });
  49517. }
  49518. labelLayout$1(data);
  49519. });
  49520. };
  49521. /*
  49522. * Licensed to the Apache Software Foundation (ASF) under one
  49523. * or more contributor license agreements. See the NOTICE file
  49524. * distributed with this work for additional information
  49525. * regarding copyright ownership. The ASF licenses this file
  49526. * to you under the Apache License, Version 2.0 (the
  49527. * "License"); you may not use this file except in compliance
  49528. * with the License. You may obtain a copy of the License at
  49529. *
  49530. * http://www.apache.org/licenses/LICENSE-2.0
  49531. *
  49532. * Unless required by applicable law or agreed to in writing,
  49533. * software distributed under the License is distributed on an
  49534. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49535. * KIND, either express or implied. See the License for the
  49536. * specific language governing permissions and limitations
  49537. * under the License.
  49538. */
  49539. registerVisual(dataColor('funnel'));
  49540. registerLayout(funnelLayout);
  49541. registerProcessor(dataFilter('funnel'));
  49542. /*
  49543. * Licensed to the Apache Software Foundation (ASF) under one
  49544. * or more contributor license agreements. See the NOTICE file
  49545. * distributed with this work for additional information
  49546. * regarding copyright ownership. The ASF licenses this file
  49547. * to you under the Apache License, Version 2.0 (the
  49548. * "License"); you may not use this file except in compliance
  49549. * with the License. You may obtain a copy of the License at
  49550. *
  49551. * http://www.apache.org/licenses/LICENSE-2.0
  49552. *
  49553. * Unless required by applicable law or agreed to in writing,
  49554. * software distributed under the License is distributed on an
  49555. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49556. * KIND, either express or implied. See the License for the
  49557. * specific language governing permissions and limitations
  49558. * under the License.
  49559. */
  49560. var parallelPreprocessor = function (option) {
  49561. createParallelIfNeeded(option);
  49562. mergeAxisOptionFromParallel(option);
  49563. };
  49564. /**
  49565. * Create a parallel coordinate if not exists.
  49566. * @inner
  49567. */
  49568. function createParallelIfNeeded(option) {
  49569. if (option.parallel) {
  49570. return;
  49571. }
  49572. var hasParallelSeries = false;
  49573. each$1(option.series, function (seriesOpt) {
  49574. if (seriesOpt && seriesOpt.type === 'parallel') {
  49575. hasParallelSeries = true;
  49576. }
  49577. });
  49578. if (hasParallelSeries) {
  49579. option.parallel = [{}];
  49580. }
  49581. }
  49582. /**
  49583. * Merge aixs definition from parallel option (if exists) to axis option.
  49584. * @inner
  49585. */
  49586. function mergeAxisOptionFromParallel(option) {
  49587. var axes = normalizeToArray(option.parallelAxis);
  49588. each$1(axes, function (axisOption) {
  49589. if (!isObject$1(axisOption)) {
  49590. return;
  49591. }
  49592. var parallelIndex = axisOption.parallelIndex || 0;
  49593. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  49594. if (parallelOption && parallelOption.parallelAxisDefault) {
  49595. merge(axisOption, parallelOption.parallelAxisDefault, false);
  49596. }
  49597. });
  49598. }
  49599. /*
  49600. * Licensed to the Apache Software Foundation (ASF) under one
  49601. * or more contributor license agreements. See the NOTICE file
  49602. * distributed with this work for additional information
  49603. * regarding copyright ownership. The ASF licenses this file
  49604. * to you under the Apache License, Version 2.0 (the
  49605. * "License"); you may not use this file except in compliance
  49606. * with the License. You may obtain a copy of the License at
  49607. *
  49608. * http://www.apache.org/licenses/LICENSE-2.0
  49609. *
  49610. * Unless required by applicable law or agreed to in writing,
  49611. * software distributed under the License is distributed on an
  49612. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49613. * KIND, either express or implied. See the License for the
  49614. * specific language governing permissions and limitations
  49615. * under the License.
  49616. */
  49617. /**
  49618. * @constructor module:echarts/coord/parallel/ParallelAxis
  49619. * @extends {module:echarts/coord/Axis}
  49620. * @param {string} dim
  49621. * @param {*} scale
  49622. * @param {Array.<number>} coordExtent
  49623. * @param {string} axisType
  49624. */
  49625. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  49626. Axis.call(this, dim, scale, coordExtent);
  49627. /**
  49628. * Axis type
  49629. * - 'category'
  49630. * - 'value'
  49631. * - 'time'
  49632. * - 'log'
  49633. * @type {string}
  49634. */
  49635. this.type = axisType || 'value';
  49636. /**
  49637. * @type {number}
  49638. * @readOnly
  49639. */
  49640. this.axisIndex = axisIndex;
  49641. };
  49642. ParallelAxis.prototype = {
  49643. constructor: ParallelAxis,
  49644. /**
  49645. * Axis model
  49646. * @param {module:echarts/coord/parallel/AxisModel}
  49647. */
  49648. model: null,
  49649. /**
  49650. * @override
  49651. */
  49652. isHorizontal: function () {
  49653. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  49654. }
  49655. };
  49656. inherits(ParallelAxis, Axis);
  49657. /*
  49658. * Licensed to the Apache Software Foundation (ASF) under one
  49659. * or more contributor license agreements. See the NOTICE file
  49660. * distributed with this work for additional information
  49661. * regarding copyright ownership. The ASF licenses this file
  49662. * to you under the Apache License, Version 2.0 (the
  49663. * "License"); you may not use this file except in compliance
  49664. * with the License. You may obtain a copy of the License at
  49665. *
  49666. * http://www.apache.org/licenses/LICENSE-2.0
  49667. *
  49668. * Unless required by applicable law or agreed to in writing,
  49669. * software distributed under the License is distributed on an
  49670. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49671. * KIND, either express or implied. See the License for the
  49672. * specific language governing permissions and limitations
  49673. * under the License.
  49674. */
  49675. /**
  49676. * Calculate slider move result.
  49677. * Usage:
  49678. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  49679. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  49680. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  49681. *
  49682. * @param {number} delta Move length.
  49683. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  49684. * handleEnds will be modified in this method.
  49685. * @param {Array.<number>} extent handleEnds is restricted by extent.
  49686. * extent[0] should less or equals than extent[1].
  49687. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  49688. * where the input minSpan and maxSpan will not work.
  49689. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  49690. * If not set, handle0 and cross handle1. If set as a non-negative
  49691. * number (including `0`), handles will push each other when reaching
  49692. * the minSpan.
  49693. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  49694. * @return {Array.<number>} The input handleEnds.
  49695. */
  49696. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  49697. // Normalize firstly.
  49698. handleEnds[0] = restrict$1(handleEnds[0], extent);
  49699. handleEnds[1] = restrict$1(handleEnds[1], extent);
  49700. delta = delta || 0;
  49701. var extentSpan = extent[1] - extent[0];
  49702. // Notice maxSpan and minSpan can be null/undefined.
  49703. if (minSpan != null) {
  49704. minSpan = restrict$1(minSpan, [0, extentSpan]);
  49705. }
  49706. if (maxSpan != null) {
  49707. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  49708. }
  49709. if (handleIndex === 'all') {
  49710. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  49711. handleIndex = 0;
  49712. }
  49713. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  49714. handleEnds[handleIndex] += delta;
  49715. // Restrict in extent.
  49716. var extentMinSpan = minSpan || 0;
  49717. var realExtent = extent.slice();
  49718. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  49719. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  49720. // Expand span.
  49721. var currDistSign = getSpanSign(handleEnds, handleIndex);
  49722. if (minSpan != null && (
  49723. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  49724. )) {
  49725. // If minSpan exists, 'cross' is forbinden.
  49726. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  49727. }
  49728. // Shrink span.
  49729. var currDistSign = getSpanSign(handleEnds, handleIndex);
  49730. if (maxSpan != null && currDistSign.span > maxSpan) {
  49731. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  49732. }
  49733. return handleEnds;
  49734. };
  49735. function getSpanSign(handleEnds, handleIndex) {
  49736. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  49737. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  49738. // is at left of handleEnds[1] for non-cross case.
  49739. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  49740. }
  49741. function restrict$1(value, extend) {
  49742. return Math.min(extend[1], Math.max(extend[0], value));
  49743. }
  49744. /*
  49745. * Licensed to the Apache Software Foundation (ASF) under one
  49746. * or more contributor license agreements. See the NOTICE file
  49747. * distributed with this work for additional information
  49748. * regarding copyright ownership. The ASF licenses this file
  49749. * to you under the Apache License, Version 2.0 (the
  49750. * "License"); you may not use this file except in compliance
  49751. * with the License. You may obtain a copy of the License at
  49752. *
  49753. * http://www.apache.org/licenses/LICENSE-2.0
  49754. *
  49755. * Unless required by applicable law or agreed to in writing,
  49756. * software distributed under the License is distributed on an
  49757. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49758. * KIND, either express or implied. See the License for the
  49759. * specific language governing permissions and limitations
  49760. * under the License.
  49761. */
  49762. /**
  49763. * Parallel Coordinates
  49764. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  49765. */
  49766. var each$11 = each$1;
  49767. var mathMin$5 = Math.min;
  49768. var mathMax$5 = Math.max;
  49769. var mathFloor$2 = Math.floor;
  49770. var mathCeil$2 = Math.ceil;
  49771. var round$3 = round$2;
  49772. var PI$3 = Math.PI;
  49773. function Parallel(parallelModel, ecModel, api) {
  49774. /**
  49775. * key: dimension
  49776. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  49777. * @private
  49778. */
  49779. this._axesMap = createHashMap();
  49780. /**
  49781. * key: dimension
  49782. * value: {position: [], rotation, }
  49783. * @type {Object.<string, Object>}
  49784. * @private
  49785. */
  49786. this._axesLayout = {};
  49787. /**
  49788. * Always follow axis order.
  49789. * @type {Array.<string>}
  49790. * @readOnly
  49791. */
  49792. this.dimensions = parallelModel.dimensions;
  49793. /**
  49794. * @type {module:zrender/core/BoundingRect}
  49795. */
  49796. this._rect;
  49797. /**
  49798. * @type {module:echarts/coord/parallel/ParallelModel}
  49799. */
  49800. this._model = parallelModel;
  49801. this._init(parallelModel, ecModel, api);
  49802. }
  49803. Parallel.prototype = {
  49804. type: 'parallel',
  49805. constructor: Parallel,
  49806. /**
  49807. * Initialize cartesian coordinate systems
  49808. * @private
  49809. */
  49810. _init: function (parallelModel, ecModel, api) {
  49811. var dimensions = parallelModel.dimensions;
  49812. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  49813. each$11(dimensions, function (dim, idx) {
  49814. var axisIndex = parallelAxisIndex[idx];
  49815. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  49816. var axis = this._axesMap.set(dim, new ParallelAxis(
  49817. dim,
  49818. createScaleByModel(axisModel),
  49819. [0, 0],
  49820. axisModel.get('type'),
  49821. axisIndex
  49822. ));
  49823. var isCategory = axis.type === 'category';
  49824. axis.onBand = isCategory && axisModel.get('boundaryGap');
  49825. axis.inverse = axisModel.get('inverse');
  49826. // Injection
  49827. axisModel.axis = axis;
  49828. axis.model = axisModel;
  49829. axis.coordinateSystem = axisModel.coordinateSystem = this;
  49830. }, this);
  49831. },
  49832. /**
  49833. * Update axis scale after data processed
  49834. * @param {module:echarts/model/Global} ecModel
  49835. * @param {module:echarts/ExtensionAPI} api
  49836. */
  49837. update: function (ecModel, api) {
  49838. this._updateAxesFromSeries(this._model, ecModel);
  49839. },
  49840. /**
  49841. * @override
  49842. */
  49843. containPoint: function (point) {
  49844. var layoutInfo = this._makeLayoutInfo();
  49845. var axisBase = layoutInfo.axisBase;
  49846. var layoutBase = layoutInfo.layoutBase;
  49847. var pixelDimIndex = layoutInfo.pixelDimIndex;
  49848. var pAxis = point[1 - pixelDimIndex];
  49849. var pLayout = point[pixelDimIndex];
  49850. return pAxis >= axisBase
  49851. && pAxis <= axisBase + layoutInfo.axisLength
  49852. && pLayout >= layoutBase
  49853. && pLayout <= layoutBase + layoutInfo.layoutLength;
  49854. },
  49855. getModel: function () {
  49856. return this._model;
  49857. },
  49858. /**
  49859. * Update properties from series
  49860. * @private
  49861. */
  49862. _updateAxesFromSeries: function (parallelModel, ecModel) {
  49863. ecModel.eachSeries(function (seriesModel) {
  49864. if (!parallelModel.contains(seriesModel, ecModel)) {
  49865. return;
  49866. }
  49867. var data = seriesModel.getData();
  49868. each$11(this.dimensions, function (dim) {
  49869. var axis = this._axesMap.get(dim);
  49870. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  49871. niceScaleExtent(axis.scale, axis.model);
  49872. }, this);
  49873. }, this);
  49874. },
  49875. /**
  49876. * Resize the parallel coordinate system.
  49877. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  49878. * @param {module:echarts/ExtensionAPI} api
  49879. */
  49880. resize: function (parallelModel, api) {
  49881. this._rect = getLayoutRect(
  49882. parallelModel.getBoxLayoutParams(),
  49883. {
  49884. width: api.getWidth(),
  49885. height: api.getHeight()
  49886. }
  49887. );
  49888. this._layoutAxes();
  49889. },
  49890. /**
  49891. * @return {module:zrender/core/BoundingRect}
  49892. */
  49893. getRect: function () {
  49894. return this._rect;
  49895. },
  49896. /**
  49897. * @private
  49898. */
  49899. _makeLayoutInfo: function () {
  49900. var parallelModel = this._model;
  49901. var rect = this._rect;
  49902. var xy = ['x', 'y'];
  49903. var wh = ['width', 'height'];
  49904. var layout = parallelModel.get('layout');
  49905. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  49906. var layoutLength = rect[wh[pixelDimIndex]];
  49907. var layoutExtent = [0, layoutLength];
  49908. var axisCount = this.dimensions.length;
  49909. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  49910. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  49911. var axisExpandable = parallelModel.get('axisExpandable')
  49912. && axisCount > 3
  49913. && axisCount > axisExpandCount
  49914. && axisExpandCount > 1
  49915. && axisExpandWidth > 0
  49916. && layoutLength > 0;
  49917. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  49918. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  49919. // where collapsed axes should be overlapped.
  49920. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  49921. var winSize;
  49922. if (!axisExpandWindow) {
  49923. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  49924. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  49925. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  49926. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  49927. }
  49928. else {
  49929. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  49930. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  49931. }
  49932. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  49933. // Avoid axisCollapseWidth is too small.
  49934. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  49935. // Find the first and last indices > ewin[0] and < ewin[1].
  49936. var winInnerIndices = [
  49937. mathFloor$2(round$3(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  49938. mathCeil$2(round$3(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  49939. ];
  49940. // Pos in ec coordinates.
  49941. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  49942. return {
  49943. layout: layout,
  49944. pixelDimIndex: pixelDimIndex,
  49945. layoutBase: rect[xy[pixelDimIndex]],
  49946. layoutLength: layoutLength,
  49947. axisBase: rect[xy[1 - pixelDimIndex]],
  49948. axisLength: rect[wh[1 - pixelDimIndex]],
  49949. axisExpandable: axisExpandable,
  49950. axisExpandWidth: axisExpandWidth,
  49951. axisCollapseWidth: axisCollapseWidth,
  49952. axisExpandWindow: axisExpandWindow,
  49953. axisCount: axisCount,
  49954. winInnerIndices: winInnerIndices,
  49955. axisExpandWindow0Pos: axisExpandWindow0Pos
  49956. };
  49957. },
  49958. /**
  49959. * @private
  49960. */
  49961. _layoutAxes: function () {
  49962. var rect = this._rect;
  49963. var axes = this._axesMap;
  49964. var dimensions = this.dimensions;
  49965. var layoutInfo = this._makeLayoutInfo();
  49966. var layout = layoutInfo.layout;
  49967. axes.each(function (axis) {
  49968. var axisExtent = [0, layoutInfo.axisLength];
  49969. var idx = axis.inverse ? 1 : 0;
  49970. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  49971. });
  49972. each$11(dimensions, function (dim, idx) {
  49973. var posInfo = (layoutInfo.axisExpandable
  49974. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  49975. )(idx, layoutInfo);
  49976. var positionTable = {
  49977. horizontal: {
  49978. x: posInfo.position,
  49979. y: layoutInfo.axisLength
  49980. },
  49981. vertical: {
  49982. x: 0,
  49983. y: posInfo.position
  49984. }
  49985. };
  49986. var rotationTable = {
  49987. horizontal: PI$3 / 2,
  49988. vertical: 0
  49989. };
  49990. var position = [
  49991. positionTable[layout].x + rect.x,
  49992. positionTable[layout].y + rect.y
  49993. ];
  49994. var rotation = rotationTable[layout];
  49995. var transform = create$1();
  49996. rotate(transform, transform, rotation);
  49997. translate(transform, transform, position);
  49998. // TODO
  49999. // tick等排布信息。
  50000. // TODO
  50001. // 根据axis order 更新 dimensions顺序。
  50002. this._axesLayout[dim] = {
  50003. position: position,
  50004. rotation: rotation,
  50005. transform: transform,
  50006. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  50007. axisLabelShow: posInfo.axisLabelShow,
  50008. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  50009. tickDirection: 1,
  50010. labelDirection: 1
  50011. };
  50012. }, this);
  50013. },
  50014. /**
  50015. * Get axis by dim.
  50016. * @param {string} dim
  50017. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  50018. */
  50019. getAxis: function (dim) {
  50020. return this._axesMap.get(dim);
  50021. },
  50022. /**
  50023. * Convert a dim value of a single item of series data to Point.
  50024. * @param {*} value
  50025. * @param {string} dim
  50026. * @return {Array}
  50027. */
  50028. dataToPoint: function (value, dim) {
  50029. return this.axisCoordToPoint(
  50030. this._axesMap.get(dim).dataToCoord(value),
  50031. dim
  50032. );
  50033. },
  50034. /**
  50035. * Travel data for one time, get activeState of each data item.
  50036. * @param {module:echarts/data/List} data
  50037. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  50038. * {number} dataIndex
  50039. * @param {number} [start=0] the start dataIndex that travel from.
  50040. * @param {number} [end=data.count()] the next dataIndex of the last dataIndex will be travel.
  50041. */
  50042. eachActiveState: function (data, callback, start, end) {
  50043. start == null && (start = 0);
  50044. end == null && (end = data.count());
  50045. var axesMap = this._axesMap;
  50046. var dimensions = this.dimensions;
  50047. var dataDimensions = [];
  50048. var axisModels = [];
  50049. each$1(dimensions, function (axisDim) {
  50050. dataDimensions.push(data.mapDimension(axisDim));
  50051. axisModels.push(axesMap.get(axisDim).model);
  50052. });
  50053. var hasActiveSet = this.hasAxisBrushed();
  50054. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  50055. var activeState;
  50056. if (!hasActiveSet) {
  50057. activeState = 'normal';
  50058. }
  50059. else {
  50060. activeState = 'active';
  50061. var values = data.getValues(dataDimensions, dataIndex);
  50062. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  50063. var state = axisModels[j].getActiveState(values[j]);
  50064. if (state === 'inactive') {
  50065. activeState = 'inactive';
  50066. break;
  50067. }
  50068. }
  50069. }
  50070. callback(activeState, dataIndex);
  50071. }
  50072. },
  50073. /**
  50074. * Whether has any activeSet.
  50075. * @return {boolean}
  50076. */
  50077. hasAxisBrushed: function () {
  50078. var dimensions = this.dimensions;
  50079. var axesMap = this._axesMap;
  50080. var hasActiveSet = false;
  50081. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  50082. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  50083. hasActiveSet = true;
  50084. }
  50085. }
  50086. return hasActiveSet;
  50087. },
  50088. /**
  50089. * Convert coords of each axis to Point.
  50090. * Return point. For example: [10, 20]
  50091. * @param {Array.<number>} coords
  50092. * @param {string} dim
  50093. * @return {Array.<number>}
  50094. */
  50095. axisCoordToPoint: function (coord, dim) {
  50096. var axisLayout = this._axesLayout[dim];
  50097. return applyTransform$1([coord, 0], axisLayout.transform);
  50098. },
  50099. /**
  50100. * Get axis layout.
  50101. */
  50102. getAxisLayout: function (dim) {
  50103. return clone(this._axesLayout[dim]);
  50104. },
  50105. /**
  50106. * @param {Array.<number>} point
  50107. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  50108. */
  50109. getSlidedAxisExpandWindow: function (point) {
  50110. var layoutInfo = this._makeLayoutInfo();
  50111. var pixelDimIndex = layoutInfo.pixelDimIndex;
  50112. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  50113. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  50114. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  50115. // Out of the area of coordinate system.
  50116. if (!this.containPoint(point)) {
  50117. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  50118. }
  50119. // Conver the point from global to expand coordinates.
  50120. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  50121. // For dragging operation convenience, the window should not be
  50122. // slided when mouse is the center area of the window.
  50123. var delta;
  50124. var behavior = 'slide';
  50125. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  50126. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  50127. // But consider touch device, jump is necessary.
  50128. var useJump = triggerArea[0] != null;
  50129. if (axisCollapseWidth) {
  50130. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  50131. behavior = 'jump';
  50132. delta = pointCoord - winSize * triggerArea[2];
  50133. }
  50134. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  50135. behavior = 'jump';
  50136. delta = pointCoord - winSize * (1 - triggerArea[2]);
  50137. }
  50138. else {
  50139. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  50140. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  50141. && (delta = 0);
  50142. }
  50143. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  50144. delta
  50145. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  50146. // Avoid nonsense triger on mousemove.
  50147. : (behavior = 'none');
  50148. }
  50149. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  50150. else {
  50151. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  50152. var pos = extent[1] * pointCoord / winSize;
  50153. axisExpandWindow = [mathMax$5(0, pos - winSize / 2)];
  50154. axisExpandWindow[1] = mathMin$5(extent[1], axisExpandWindow[0] + winSize);
  50155. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  50156. }
  50157. return {
  50158. axisExpandWindow: axisExpandWindow,
  50159. behavior: behavior
  50160. };
  50161. }
  50162. };
  50163. function restrict(len, extent) {
  50164. return mathMin$5(mathMax$5(len, extent[0]), extent[1]);
  50165. }
  50166. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  50167. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  50168. return {
  50169. position: step * axisIndex,
  50170. axisNameAvailableWidth: step,
  50171. axisLabelShow: true
  50172. };
  50173. }
  50174. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  50175. var layoutLength = layoutInfo.layoutLength;
  50176. var axisExpandWidth = layoutInfo.axisExpandWidth;
  50177. var axisCount = layoutInfo.axisCount;
  50178. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  50179. var winInnerIndices = layoutInfo.winInnerIndices;
  50180. var position;
  50181. var axisNameAvailableWidth = axisCollapseWidth;
  50182. var axisLabelShow = false;
  50183. var nameTruncateMaxWidth;
  50184. if (axisIndex < winInnerIndices[0]) {
  50185. position = axisIndex * axisCollapseWidth;
  50186. nameTruncateMaxWidth = axisCollapseWidth;
  50187. }
  50188. else if (axisIndex <= winInnerIndices[1]) {
  50189. position = layoutInfo.axisExpandWindow0Pos
  50190. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  50191. axisNameAvailableWidth = axisExpandWidth;
  50192. axisLabelShow = true;
  50193. }
  50194. else {
  50195. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  50196. nameTruncateMaxWidth = axisCollapseWidth;
  50197. }
  50198. return {
  50199. position: position,
  50200. axisNameAvailableWidth: axisNameAvailableWidth,
  50201. axisLabelShow: axisLabelShow,
  50202. nameTruncateMaxWidth: nameTruncateMaxWidth
  50203. };
  50204. }
  50205. /*
  50206. * Licensed to the Apache Software Foundation (ASF) under one
  50207. * or more contributor license agreements. See the NOTICE file
  50208. * distributed with this work for additional information
  50209. * regarding copyright ownership. The ASF licenses this file
  50210. * to you under the Apache License, Version 2.0 (the
  50211. * "License"); you may not use this file except in compliance
  50212. * with the License. You may obtain a copy of the License at
  50213. *
  50214. * http://www.apache.org/licenses/LICENSE-2.0
  50215. *
  50216. * Unless required by applicable law or agreed to in writing,
  50217. * software distributed under the License is distributed on an
  50218. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50219. * KIND, either express or implied. See the License for the
  50220. * specific language governing permissions and limitations
  50221. * under the License.
  50222. */
  50223. /**
  50224. * Parallel coordinate system creater.
  50225. */
  50226. function create$2(ecModel, api) {
  50227. var coordSysList = [];
  50228. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  50229. var coordSys = new Parallel(parallelModel, ecModel, api);
  50230. coordSys.name = 'parallel_' + idx;
  50231. coordSys.resize(parallelModel, api);
  50232. parallelModel.coordinateSystem = coordSys;
  50233. coordSys.model = parallelModel;
  50234. coordSysList.push(coordSys);
  50235. });
  50236. // Inject the coordinateSystems into seriesModel
  50237. ecModel.eachSeries(function (seriesModel) {
  50238. if (seriesModel.get('coordinateSystem') === 'parallel') {
  50239. var parallelModel = ecModel.queryComponents({
  50240. mainType: 'parallel',
  50241. index: seriesModel.get('parallelIndex'),
  50242. id: seriesModel.get('parallelId')
  50243. })[0];
  50244. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  50245. }
  50246. });
  50247. return coordSysList;
  50248. }
  50249. CoordinateSystemManager.register('parallel', {create: create$2});
  50250. /*
  50251. * Licensed to the Apache Software Foundation (ASF) under one
  50252. * or more contributor license agreements. See the NOTICE file
  50253. * distributed with this work for additional information
  50254. * regarding copyright ownership. The ASF licenses this file
  50255. * to you under the Apache License, Version 2.0 (the
  50256. * "License"); you may not use this file except in compliance
  50257. * with the License. You may obtain a copy of the License at
  50258. *
  50259. * http://www.apache.org/licenses/LICENSE-2.0
  50260. *
  50261. * Unless required by applicable law or agreed to in writing,
  50262. * software distributed under the License is distributed on an
  50263. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50264. * KIND, either express or implied. See the License for the
  50265. * specific language governing permissions and limitations
  50266. * under the License.
  50267. */
  50268. var AxisModel$2 = ComponentModel.extend({
  50269. type: 'baseParallelAxis',
  50270. /**
  50271. * @type {module:echarts/coord/parallel/Axis}
  50272. */
  50273. axis: null,
  50274. /**
  50275. * @type {Array.<Array.<number>}
  50276. * @readOnly
  50277. */
  50278. activeIntervals: [],
  50279. /**
  50280. * @return {Object}
  50281. */
  50282. getAreaSelectStyle: function () {
  50283. return makeStyleMapper(
  50284. [
  50285. ['fill', 'color'],
  50286. ['lineWidth', 'borderWidth'],
  50287. ['stroke', 'borderColor'],
  50288. ['width', 'width'],
  50289. ['opacity', 'opacity']
  50290. ]
  50291. )(this.getModel('areaSelectStyle'));
  50292. },
  50293. /**
  50294. * The code of this feature is put on AxisModel but not ParallelAxis,
  50295. * because axisModel can be alive after echarts updating but instance of
  50296. * ParallelAxis having been disposed. this._activeInterval should be kept
  50297. * when action dispatched (i.e. legend click).
  50298. *
  50299. * @param {Array.<Array<number>>} intervals interval.length === 0
  50300. * means set all active.
  50301. * @public
  50302. */
  50303. setActiveIntervals: function (intervals) {
  50304. var activeIntervals = this.activeIntervals = clone(intervals);
  50305. // Normalize
  50306. if (activeIntervals) {
  50307. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  50308. asc(activeIntervals[i]);
  50309. }
  50310. }
  50311. },
  50312. /**
  50313. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  50314. * value can not be input.
  50315. * @return {string} 'normal': no activeIntervals set,
  50316. * 'active',
  50317. * 'inactive'.
  50318. * @public
  50319. */
  50320. getActiveState: function (value) {
  50321. var activeIntervals = this.activeIntervals;
  50322. if (!activeIntervals.length) {
  50323. return 'normal';
  50324. }
  50325. if (value == null || isNaN(value)) {
  50326. return 'inactive';
  50327. }
  50328. // Simple optimization
  50329. if (activeIntervals.length === 1) {
  50330. var interval = activeIntervals[0];
  50331. if (interval[0] <= value && value <= interval[1]) {
  50332. return 'active';
  50333. }
  50334. }
  50335. else {
  50336. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  50337. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  50338. return 'active';
  50339. }
  50340. }
  50341. }
  50342. return 'inactive';
  50343. }
  50344. });
  50345. var defaultOption$1 = {
  50346. type: 'value',
  50347. /**
  50348. * @type {Array.<number>}
  50349. */
  50350. dim: null, // 0, 1, 2, ...
  50351. // parallelIndex: null,
  50352. areaSelectStyle: {
  50353. width: 20,
  50354. borderWidth: 1,
  50355. borderColor: 'rgba(160,197,232)',
  50356. color: 'rgba(160,197,232)',
  50357. opacity: 0.3
  50358. },
  50359. realtime: true, // Whether realtime update view when select.
  50360. z: 10
  50361. };
  50362. merge(AxisModel$2.prototype, axisModelCommonMixin);
  50363. function getAxisType$1(axisName, option) {
  50364. return option.type || (option.data ? 'category' : 'value');
  50365. }
  50366. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  50367. /*
  50368. * Licensed to the Apache Software Foundation (ASF) under one
  50369. * or more contributor license agreements. See the NOTICE file
  50370. * distributed with this work for additional information
  50371. * regarding copyright ownership. The ASF licenses this file
  50372. * to you under the Apache License, Version 2.0 (the
  50373. * "License"); you may not use this file except in compliance
  50374. * with the License. You may obtain a copy of the License at
  50375. *
  50376. * http://www.apache.org/licenses/LICENSE-2.0
  50377. *
  50378. * Unless required by applicable law or agreed to in writing,
  50379. * software distributed under the License is distributed on an
  50380. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50381. * KIND, either express or implied. See the License for the
  50382. * specific language governing permissions and limitations
  50383. * under the License.
  50384. */
  50385. ComponentModel.extend({
  50386. type: 'parallel',
  50387. dependencies: ['parallelAxis'],
  50388. /**
  50389. * @type {module:echarts/coord/parallel/Parallel}
  50390. */
  50391. coordinateSystem: null,
  50392. /**
  50393. * Each item like: 'dim0', 'dim1', 'dim2', ...
  50394. * @type {Array.<string>}
  50395. * @readOnly
  50396. */
  50397. dimensions: null,
  50398. /**
  50399. * Coresponding to dimensions.
  50400. * @type {Array.<number>}
  50401. * @readOnly
  50402. */
  50403. parallelAxisIndex: null,
  50404. layoutMode: 'box',
  50405. defaultOption: {
  50406. zlevel: 0,
  50407. z: 0,
  50408. left: 80,
  50409. top: 60,
  50410. right: 80,
  50411. bottom: 60,
  50412. // width: {totalWidth} - left - right,
  50413. // height: {totalHeight} - top - bottom,
  50414. layout: 'horizontal', // 'horizontal' or 'vertical'
  50415. // FIXME
  50416. // naming?
  50417. axisExpandable: false,
  50418. axisExpandCenter: null,
  50419. axisExpandCount: 0,
  50420. axisExpandWidth: 50, // FIXME '10%' ?
  50421. axisExpandRate: 17,
  50422. axisExpandDebounce: 50,
  50423. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  50424. // Do not doc to user until necessary.
  50425. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  50426. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  50427. parallelAxisDefault: null
  50428. },
  50429. /**
  50430. * @override
  50431. */
  50432. init: function () {
  50433. ComponentModel.prototype.init.apply(this, arguments);
  50434. this.mergeOption({});
  50435. },
  50436. /**
  50437. * @override
  50438. */
  50439. mergeOption: function (newOption) {
  50440. var thisOption = this.option;
  50441. newOption && merge(thisOption, newOption, true);
  50442. this._initDimensions();
  50443. },
  50444. /**
  50445. * Whether series or axis is in this coordinate system.
  50446. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  50447. * @param {module:echarts/model/Global} ecModel
  50448. */
  50449. contains: function (model, ecModel) {
  50450. var parallelIndex = model.get('parallelIndex');
  50451. return parallelIndex != null
  50452. && ecModel.getComponent('parallel', parallelIndex) === this;
  50453. },
  50454. setAxisExpand: function (opt) {
  50455. each$1(
  50456. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  50457. function (name) {
  50458. if (opt.hasOwnProperty(name)) {
  50459. this.option[name] = opt[name];
  50460. }
  50461. },
  50462. this
  50463. );
  50464. },
  50465. /**
  50466. * @private
  50467. */
  50468. _initDimensions: function () {
  50469. var dimensions = this.dimensions = [];
  50470. var parallelAxisIndex = this.parallelAxisIndex = [];
  50471. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  50472. // Can not use this.contains here, because
  50473. // initialization has not been completed yet.
  50474. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  50475. }, this);
  50476. each$1(axisModels, function (axisModel) {
  50477. dimensions.push('dim' + axisModel.get('dim'));
  50478. parallelAxisIndex.push(axisModel.componentIndex);
  50479. });
  50480. }
  50481. });
  50482. /*
  50483. * Licensed to the Apache Software Foundation (ASF) under one
  50484. * or more contributor license agreements. See the NOTICE file
  50485. * distributed with this work for additional information
  50486. * regarding copyright ownership. The ASF licenses this file
  50487. * to you under the Apache License, Version 2.0 (the
  50488. * "License"); you may not use this file except in compliance
  50489. * with the License. You may obtain a copy of the License at
  50490. *
  50491. * http://www.apache.org/licenses/LICENSE-2.0
  50492. *
  50493. * Unless required by applicable law or agreed to in writing,
  50494. * software distributed under the License is distributed on an
  50495. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50496. * KIND, either express or implied. See the License for the
  50497. * specific language governing permissions and limitations
  50498. * under the License.
  50499. */
  50500. /**
  50501. * @payload
  50502. * @property {string} parallelAxisId
  50503. * @property {Array.<Array.<number>>} intervals
  50504. */
  50505. var actionInfo$1 = {
  50506. type: 'axisAreaSelect',
  50507. event: 'axisAreaSelected'
  50508. // update: 'updateVisual'
  50509. };
  50510. registerAction(actionInfo$1, function (payload, ecModel) {
  50511. ecModel.eachComponent(
  50512. {mainType: 'parallelAxis', query: payload},
  50513. function (parallelAxisModel) {
  50514. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  50515. }
  50516. );
  50517. });
  50518. /**
  50519. * @payload
  50520. */
  50521. registerAction('parallelAxisExpand', function (payload, ecModel) {
  50522. ecModel.eachComponent(
  50523. {mainType: 'parallel', query: payload},
  50524. function (parallelModel) {
  50525. parallelModel.setAxisExpand(payload);
  50526. }
  50527. );
  50528. });
  50529. /*
  50530. * Licensed to the Apache Software Foundation (ASF) under one
  50531. * or more contributor license agreements. See the NOTICE file
  50532. * distributed with this work for additional information
  50533. * regarding copyright ownership. The ASF licenses this file
  50534. * to you under the Apache License, Version 2.0 (the
  50535. * "License"); you may not use this file except in compliance
  50536. * with the License. You may obtain a copy of the License at
  50537. *
  50538. * http://www.apache.org/licenses/LICENSE-2.0
  50539. *
  50540. * Unless required by applicable law or agreed to in writing,
  50541. * software distributed under the License is distributed on an
  50542. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50543. * KIND, either express or implied. See the License for the
  50544. * specific language governing permissions and limitations
  50545. * under the License.
  50546. */
  50547. var curry$2 = curry;
  50548. var each$12 = each$1;
  50549. var map$2 = map;
  50550. var mathMin$6 = Math.min;
  50551. var mathMax$6 = Math.max;
  50552. var mathPow$2 = Math.pow;
  50553. var COVER_Z = 10000;
  50554. var UNSELECT_THRESHOLD = 6;
  50555. var MIN_RESIZE_LINE_WIDTH = 6;
  50556. var MUTEX_RESOURCE_KEY = 'globalPan';
  50557. var DIRECTION_MAP = {
  50558. w: [0, 0],
  50559. e: [0, 1],
  50560. n: [1, 0],
  50561. s: [1, 1]
  50562. };
  50563. var CURSOR_MAP = {
  50564. w: 'ew',
  50565. e: 'ew',
  50566. n: 'ns',
  50567. s: 'ns',
  50568. ne: 'nesw',
  50569. sw: 'nesw',
  50570. nw: 'nwse',
  50571. se: 'nwse'
  50572. };
  50573. var DEFAULT_BRUSH_OPT = {
  50574. brushStyle: {
  50575. lineWidth: 2,
  50576. stroke: 'rgba(0,0,0,0.3)',
  50577. fill: 'rgba(0,0,0,0.1)'
  50578. },
  50579. transformable: true,
  50580. brushMode: 'single',
  50581. removeOnClick: false
  50582. };
  50583. var baseUID = 0;
  50584. /**
  50585. * @alias module:echarts/component/helper/BrushController
  50586. * @constructor
  50587. * @mixin {module:zrender/mixin/Eventful}
  50588. * @event module:echarts/component/helper/BrushController#brush
  50589. * params:
  50590. * areas: Array.<Array>, coord relates to container group,
  50591. * If no container specified, to global.
  50592. * opt {
  50593. * isEnd: boolean,
  50594. * removeOnClick: boolean
  50595. * }
  50596. *
  50597. * @param {module:zrender/zrender~ZRender} zr
  50598. */
  50599. function BrushController(zr) {
  50600. if (__DEV__) {
  50601. assert$1(zr);
  50602. }
  50603. Eventful.call(this);
  50604. /**
  50605. * @type {module:zrender/zrender~ZRender}
  50606. * @private
  50607. */
  50608. this._zr = zr;
  50609. /**
  50610. * @type {module:zrender/container/Group}
  50611. * @readOnly
  50612. */
  50613. this.group = new Group();
  50614. /**
  50615. * Only for drawing (after enabledBrush).
  50616. * 'line', 'rect', 'polygon' or false
  50617. * If passing false/null/undefined, disable brush.
  50618. * If passing 'auto', determined by panel.defaultBrushType
  50619. * @private
  50620. * @type {string}
  50621. */
  50622. this._brushType;
  50623. /**
  50624. * Only for drawing (after enabledBrush).
  50625. *
  50626. * @private
  50627. * @type {Object}
  50628. */
  50629. this._brushOption;
  50630. /**
  50631. * @private
  50632. * @type {Object}
  50633. */
  50634. this._panels;
  50635. /**
  50636. * @private
  50637. * @type {Array.<nubmer>}
  50638. */
  50639. this._track = [];
  50640. /**
  50641. * @private
  50642. * @type {boolean}
  50643. */
  50644. this._dragging;
  50645. /**
  50646. * @private
  50647. * @type {Array}
  50648. */
  50649. this._covers = [];
  50650. /**
  50651. * @private
  50652. * @type {moudule:zrender/container/Group}
  50653. */
  50654. this._creatingCover;
  50655. /**
  50656. * `true` means global panel
  50657. * @private
  50658. * @type {module:zrender/container/Group|boolean}
  50659. */
  50660. this._creatingPanel;
  50661. /**
  50662. * @private
  50663. * @type {boolean}
  50664. */
  50665. this._enableGlobalPan;
  50666. /**
  50667. * @private
  50668. * @type {boolean}
  50669. */
  50670. if (__DEV__) {
  50671. this._mounted;
  50672. }
  50673. /**
  50674. * @private
  50675. * @type {string}
  50676. */
  50677. this._uid = 'brushController_' + baseUID++;
  50678. /**
  50679. * @private
  50680. * @type {Object}
  50681. */
  50682. this._handlers = {};
  50683. each$12(mouseHandlers, function (handler, eventName) {
  50684. this._handlers[eventName] = bind(handler, this);
  50685. }, this);
  50686. }
  50687. BrushController.prototype = {
  50688. constructor: BrushController,
  50689. /**
  50690. * If set to null/undefined/false, select disabled.
  50691. * @param {Object} brushOption
  50692. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  50693. * If passing false/null/undefined, disable brush.
  50694. * If passing 'auto', determined by panel.defaultBrushType.
  50695. * ('auto' can not be used in global panel)
  50696. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  50697. * @param {boolean} [brushOption.transformable=true]
  50698. * @param {boolean} [brushOption.removeOnClick=false]
  50699. * @param {Object} [brushOption.brushStyle]
  50700. * @param {number} [brushOption.brushStyle.width]
  50701. * @param {number} [brushOption.brushStyle.lineWidth]
  50702. * @param {string} [brushOption.brushStyle.stroke]
  50703. * @param {string} [brushOption.brushStyle.fill]
  50704. * @param {number} [brushOption.z]
  50705. */
  50706. enableBrush: function (brushOption) {
  50707. if (__DEV__) {
  50708. assert$1(this._mounted);
  50709. }
  50710. this._brushType && doDisableBrush(this);
  50711. brushOption.brushType && doEnableBrush(this, brushOption);
  50712. return this;
  50713. },
  50714. /**
  50715. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  50716. * Each items: {
  50717. * panelId, // mandatory.
  50718. * clipPath, // mandatory. function.
  50719. * isTargetByCursor, // mandatory. function.
  50720. * defaultBrushType, // optional, only used when brushType is 'auto'.
  50721. * getLinearBrushOtherExtent, // optional. function.
  50722. * }
  50723. */
  50724. setPanels: function (panelOpts) {
  50725. if (panelOpts && panelOpts.length) {
  50726. var panels = this._panels = {};
  50727. each$1(panelOpts, function (panelOpts) {
  50728. panels[panelOpts.panelId] = clone(panelOpts);
  50729. });
  50730. }
  50731. else {
  50732. this._panels = null;
  50733. }
  50734. return this;
  50735. },
  50736. /**
  50737. * @param {Object} [opt]
  50738. * @return {boolean} [opt.enableGlobalPan=false]
  50739. */
  50740. mount: function (opt) {
  50741. opt = opt || {};
  50742. if (__DEV__) {
  50743. this._mounted = true; // should be at first.
  50744. }
  50745. this._enableGlobalPan = opt.enableGlobalPan;
  50746. var thisGroup = this.group;
  50747. this._zr.add(thisGroup);
  50748. thisGroup.attr({
  50749. position: opt.position || [0, 0],
  50750. rotation: opt.rotation || 0,
  50751. scale: opt.scale || [1, 1]
  50752. });
  50753. this._transform = thisGroup.getLocalTransform();
  50754. return this;
  50755. },
  50756. eachCover: function (cb, context) {
  50757. each$12(this._covers, cb, context);
  50758. },
  50759. /**
  50760. * Update covers.
  50761. * @param {Array.<Object>} brushOptionList Like:
  50762. * [
  50763. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  50764. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  50765. * ...
  50766. * ]
  50767. * `brushType` is required in each cover info. (can not be 'auto')
  50768. * `id` is not mandatory.
  50769. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  50770. * If brushOptionList is null/undefined, all covers removed.
  50771. */
  50772. updateCovers: function (brushOptionList) {
  50773. if (__DEV__) {
  50774. assert$1(this._mounted);
  50775. }
  50776. brushOptionList = map(brushOptionList, function (brushOption) {
  50777. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  50778. });
  50779. var tmpIdPrefix = '\0-brush-index-';
  50780. var oldCovers = this._covers;
  50781. var newCovers = this._covers = [];
  50782. var controller = this;
  50783. var creatingCover = this._creatingCover;
  50784. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  50785. .add(addOrUpdate)
  50786. .update(addOrUpdate)
  50787. .remove(remove)
  50788. .execute();
  50789. return this;
  50790. function getKey(brushOption, index) {
  50791. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  50792. + '-' + brushOption.brushType;
  50793. }
  50794. function oldGetKey(cover, index) {
  50795. return getKey(cover.__brushOption, index);
  50796. }
  50797. function addOrUpdate(newIndex, oldIndex) {
  50798. var newBrushOption = brushOptionList[newIndex];
  50799. // Consider setOption in event listener of brushSelect,
  50800. // where updating cover when creating should be forbiden.
  50801. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  50802. newCovers[newIndex] = oldCovers[oldIndex];
  50803. }
  50804. else {
  50805. var cover = newCovers[newIndex] = oldIndex != null
  50806. ? (
  50807. oldCovers[oldIndex].__brushOption = newBrushOption,
  50808. oldCovers[oldIndex]
  50809. )
  50810. : endCreating(controller, createCover(controller, newBrushOption));
  50811. updateCoverAfterCreation(controller, cover);
  50812. }
  50813. }
  50814. function remove(oldIndex) {
  50815. if (oldCovers[oldIndex] !== creatingCover) {
  50816. controller.group.remove(oldCovers[oldIndex]);
  50817. }
  50818. }
  50819. },
  50820. unmount: function () {
  50821. if (__DEV__) {
  50822. if (!this._mounted) {
  50823. return;
  50824. }
  50825. }
  50826. this.enableBrush(false);
  50827. // container may 'removeAll' outside.
  50828. clearCovers(this);
  50829. this._zr.remove(this.group);
  50830. if (__DEV__) {
  50831. this._mounted = false; // should be at last.
  50832. }
  50833. return this;
  50834. },
  50835. dispose: function () {
  50836. this.unmount();
  50837. this.off();
  50838. }
  50839. };
  50840. mixin(BrushController, Eventful);
  50841. function doEnableBrush(controller, brushOption) {
  50842. var zr = controller._zr;
  50843. // Consider roam, which takes globalPan too.
  50844. if (!controller._enableGlobalPan) {
  50845. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  50846. }
  50847. each$12(controller._handlers, function (handler, eventName) {
  50848. zr.on(eventName, handler);
  50849. });
  50850. controller._brushType = brushOption.brushType;
  50851. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  50852. }
  50853. function doDisableBrush(controller) {
  50854. var zr = controller._zr;
  50855. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  50856. each$12(controller._handlers, function (handler, eventName) {
  50857. zr.off(eventName, handler);
  50858. });
  50859. controller._brushType = controller._brushOption = null;
  50860. }
  50861. function createCover(controller, brushOption) {
  50862. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  50863. cover.__brushOption = brushOption;
  50864. updateZ$1(cover, brushOption);
  50865. controller.group.add(cover);
  50866. return cover;
  50867. }
  50868. function endCreating(controller, creatingCover) {
  50869. var coverRenderer = getCoverRenderer(creatingCover);
  50870. if (coverRenderer.endCreating) {
  50871. coverRenderer.endCreating(controller, creatingCover);
  50872. updateZ$1(creatingCover, creatingCover.__brushOption);
  50873. }
  50874. return creatingCover;
  50875. }
  50876. function updateCoverShape(controller, cover) {
  50877. var brushOption = cover.__brushOption;
  50878. getCoverRenderer(cover).updateCoverShape(
  50879. controller, cover, brushOption.range, brushOption
  50880. );
  50881. }
  50882. function updateZ$1(cover, brushOption) {
  50883. var z = brushOption.z;
  50884. z == null && (z = COVER_Z);
  50885. cover.traverse(function (el) {
  50886. el.z = z;
  50887. el.z2 = z; // Consider in given container.
  50888. });
  50889. }
  50890. function updateCoverAfterCreation(controller, cover) {
  50891. getCoverRenderer(cover).updateCommon(controller, cover);
  50892. updateCoverShape(controller, cover);
  50893. }
  50894. function getCoverRenderer(cover) {
  50895. return coverRenderers[cover.__brushOption.brushType];
  50896. }
  50897. // return target panel or `true` (means global panel)
  50898. function getPanelByPoint(controller, e, localCursorPoint) {
  50899. var panels = controller._panels;
  50900. if (!panels) {
  50901. return true; // Global panel
  50902. }
  50903. var panel;
  50904. var transform = controller._transform;
  50905. each$12(panels, function (pn) {
  50906. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  50907. });
  50908. return panel;
  50909. }
  50910. // Return a panel or true
  50911. function getPanelByCover(controller, cover) {
  50912. var panels = controller._panels;
  50913. if (!panels) {
  50914. return true; // Global panel
  50915. }
  50916. var panelId = cover.__brushOption.panelId;
  50917. // User may give cover without coord sys info,
  50918. // which is then treated as global panel.
  50919. return panelId != null ? panels[panelId] : true;
  50920. }
  50921. function clearCovers(controller) {
  50922. var covers = controller._covers;
  50923. var originalLength = covers.length;
  50924. each$12(covers, function (cover) {
  50925. controller.group.remove(cover);
  50926. }, controller);
  50927. covers.length = 0;
  50928. return !!originalLength;
  50929. }
  50930. function trigger$1(controller, opt) {
  50931. var areas = map$2(controller._covers, function (cover) {
  50932. var brushOption = cover.__brushOption;
  50933. var range = clone(brushOption.range);
  50934. return {
  50935. brushType: brushOption.brushType,
  50936. panelId: brushOption.panelId,
  50937. range: range
  50938. };
  50939. });
  50940. controller.trigger('brush', areas, {
  50941. isEnd: !!opt.isEnd,
  50942. removeOnClick: !!opt.removeOnClick
  50943. });
  50944. }
  50945. function shouldShowCover(controller) {
  50946. var track = controller._track;
  50947. if (!track.length) {
  50948. return false;
  50949. }
  50950. var p2 = track[track.length - 1];
  50951. var p1 = track[0];
  50952. var dx = p2[0] - p1[0];
  50953. var dy = p2[1] - p1[1];
  50954. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  50955. return dist > UNSELECT_THRESHOLD;
  50956. }
  50957. function getTrackEnds(track) {
  50958. var tail = track.length - 1;
  50959. tail < 0 && (tail = 0);
  50960. return [track[0], track[tail]];
  50961. }
  50962. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  50963. var cover = new Group();
  50964. cover.add(new Rect({
  50965. name: 'main',
  50966. style: makeStyle(brushOption),
  50967. silent: true,
  50968. draggable: true,
  50969. cursor: 'move',
  50970. drift: curry$2(doDrift, controller, cover, 'nswe'),
  50971. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  50972. }));
  50973. each$12(
  50974. edgeNames,
  50975. function (name) {
  50976. cover.add(new Rect({
  50977. name: name,
  50978. style: {opacity: 0},
  50979. draggable: true,
  50980. silent: true,
  50981. invisible: true,
  50982. drift: curry$2(doDrift, controller, cover, name),
  50983. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  50984. }));
  50985. }
  50986. );
  50987. return cover;
  50988. }
  50989. function updateBaseRect(controller, cover, localRange, brushOption) {
  50990. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  50991. var handleSize = mathMax$6(lineWidth, MIN_RESIZE_LINE_WIDTH);
  50992. var x = localRange[0][0];
  50993. var y = localRange[1][0];
  50994. var xa = x - lineWidth / 2;
  50995. var ya = y - lineWidth / 2;
  50996. var x2 = localRange[0][1];
  50997. var y2 = localRange[1][1];
  50998. var x2a = x2 - handleSize + lineWidth / 2;
  50999. var y2a = y2 - handleSize + lineWidth / 2;
  51000. var width = x2 - x;
  51001. var height = y2 - y;
  51002. var widtha = width + lineWidth;
  51003. var heighta = height + lineWidth;
  51004. updateRectShape(controller, cover, 'main', x, y, width, height);
  51005. if (brushOption.transformable) {
  51006. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  51007. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  51008. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  51009. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  51010. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  51011. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  51012. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  51013. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  51014. }
  51015. }
  51016. function updateCommon(controller, cover) {
  51017. var brushOption = cover.__brushOption;
  51018. var transformable = brushOption.transformable;
  51019. var mainEl = cover.childAt(0);
  51020. mainEl.useStyle(makeStyle(brushOption));
  51021. mainEl.attr({
  51022. silent: !transformable,
  51023. cursor: transformable ? 'move' : 'default'
  51024. });
  51025. each$12(
  51026. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  51027. function (name) {
  51028. var el = cover.childOfName(name);
  51029. var globalDir = getGlobalDirection(controller, name);
  51030. el && el.attr({
  51031. silent: !transformable,
  51032. invisible: !transformable,
  51033. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  51034. });
  51035. }
  51036. );
  51037. }
  51038. function updateRectShape(controller, cover, name, x, y, w, h) {
  51039. var el = cover.childOfName(name);
  51040. el && el.setShape(pointsToRect(
  51041. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  51042. ));
  51043. }
  51044. function makeStyle(brushOption) {
  51045. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  51046. }
  51047. function formatRectRange(x, y, x2, y2) {
  51048. var min = [mathMin$6(x, x2), mathMin$6(y, y2)];
  51049. var max = [mathMax$6(x, x2), mathMax$6(y, y2)];
  51050. return [
  51051. [min[0], max[0]], // x range
  51052. [min[1], max[1]] // y range
  51053. ];
  51054. }
  51055. function getTransform$1(controller) {
  51056. return getTransform(controller.group);
  51057. }
  51058. function getGlobalDirection(controller, localDirection) {
  51059. if (localDirection.length > 1) {
  51060. localDirection = localDirection.split('');
  51061. var globalDir = [
  51062. getGlobalDirection(controller, localDirection[0]),
  51063. getGlobalDirection(controller, localDirection[1])
  51064. ];
  51065. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  51066. return globalDir.join('');
  51067. }
  51068. else {
  51069. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  51070. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  51071. var globalDir = transformDirection(
  51072. map$$1[localDirection], getTransform$1(controller)
  51073. );
  51074. return inverseMap[globalDir];
  51075. }
  51076. }
  51077. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  51078. var brushOption = cover.__brushOption;
  51079. var rectRange = toRectRange(brushOption.range);
  51080. var localDelta = toLocalDelta(controller, dx, dy);
  51081. each$12(name.split(''), function (namePart) {
  51082. var ind = DIRECTION_MAP[namePart];
  51083. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  51084. });
  51085. brushOption.range = fromRectRange(formatRectRange(
  51086. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  51087. ));
  51088. updateCoverAfterCreation(controller, cover);
  51089. trigger$1(controller, {isEnd: false});
  51090. }
  51091. function driftPolygon(controller, cover, dx, dy, e) {
  51092. var range = cover.__brushOption.range;
  51093. var localDelta = toLocalDelta(controller, dx, dy);
  51094. each$12(range, function (point) {
  51095. point[0] += localDelta[0];
  51096. point[1] += localDelta[1];
  51097. });
  51098. updateCoverAfterCreation(controller, cover);
  51099. trigger$1(controller, {isEnd: false});
  51100. }
  51101. function toLocalDelta(controller, dx, dy) {
  51102. var thisGroup = controller.group;
  51103. var localD = thisGroup.transformCoordToLocal(dx, dy);
  51104. var localZero = thisGroup.transformCoordToLocal(0, 0);
  51105. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  51106. }
  51107. function clipByPanel(controller, cover, data) {
  51108. var panel = getPanelByCover(controller, cover);
  51109. return (panel && panel !== true)
  51110. ? panel.clipPath(data, controller._transform)
  51111. : clone(data);
  51112. }
  51113. function pointsToRect(points) {
  51114. var xmin = mathMin$6(points[0][0], points[1][0]);
  51115. var ymin = mathMin$6(points[0][1], points[1][1]);
  51116. var xmax = mathMax$6(points[0][0], points[1][0]);
  51117. var ymax = mathMax$6(points[0][1], points[1][1]);
  51118. return {
  51119. x: xmin,
  51120. y: ymin,
  51121. width: xmax - xmin,
  51122. height: ymax - ymin
  51123. };
  51124. }
  51125. function resetCursor(controller, e, localCursorPoint) {
  51126. // Check active
  51127. if (!controller._brushType) {
  51128. return;
  51129. }
  51130. var zr = controller._zr;
  51131. var covers = controller._covers;
  51132. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  51133. // Check whether in covers.
  51134. if (!controller._dragging) {
  51135. for (var i = 0; i < covers.length; i++) {
  51136. var brushOption = covers[i].__brushOption;
  51137. if (currPanel
  51138. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  51139. && coverRenderers[brushOption.brushType].contain(
  51140. covers[i], localCursorPoint[0], localCursorPoint[1]
  51141. )
  51142. ) {
  51143. // Use cursor style set on cover.
  51144. return;
  51145. }
  51146. }
  51147. }
  51148. currPanel && zr.setCursorStyle('crosshair');
  51149. }
  51150. function preventDefault(e) {
  51151. var rawE = e.event;
  51152. rawE.preventDefault && rawE.preventDefault();
  51153. }
  51154. function mainShapeContain(cover, x, y) {
  51155. return cover.childOfName('main').contain(x, y);
  51156. }
  51157. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  51158. var creatingCover = controller._creatingCover;
  51159. var panel = controller._creatingPanel;
  51160. var thisBrushOption = controller._brushOption;
  51161. var eventParams;
  51162. controller._track.push(localCursorPoint.slice());
  51163. if (shouldShowCover(controller) || creatingCover) {
  51164. if (panel && !creatingCover) {
  51165. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  51166. var brushOption = clone(thisBrushOption);
  51167. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  51168. brushOption.panelId = panel === true ? null : panel.panelId;
  51169. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  51170. controller._covers.push(creatingCover);
  51171. }
  51172. if (creatingCover) {
  51173. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  51174. var coverBrushOption = creatingCover.__brushOption;
  51175. coverBrushOption.range = coverRenderer.getCreatingRange(
  51176. clipByPanel(controller, creatingCover, controller._track)
  51177. );
  51178. if (isEnd) {
  51179. endCreating(controller, creatingCover);
  51180. coverRenderer.updateCommon(controller, creatingCover);
  51181. }
  51182. updateCoverShape(controller, creatingCover);
  51183. eventParams = {isEnd: isEnd};
  51184. }
  51185. }
  51186. else if (
  51187. isEnd
  51188. && thisBrushOption.brushMode === 'single'
  51189. && thisBrushOption.removeOnClick
  51190. ) {
  51191. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  51192. // But a single click do not clear covers, because user may have casual
  51193. // clicks (for example, click on other component and do not expect covers
  51194. // disappear).
  51195. // Only some cover removed, trigger action, but not every click trigger action.
  51196. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  51197. eventParams = {isEnd: isEnd, removeOnClick: true};
  51198. }
  51199. }
  51200. return eventParams;
  51201. }
  51202. function determineBrushType(brushType, panel) {
  51203. if (brushType === 'auto') {
  51204. if (__DEV__) {
  51205. assert$1(
  51206. panel && panel.defaultBrushType,
  51207. 'MUST have defaultBrushType when brushType is "atuo"'
  51208. );
  51209. }
  51210. return panel.defaultBrushType;
  51211. }
  51212. return brushType;
  51213. }
  51214. var mouseHandlers = {
  51215. mousedown: function (e) {
  51216. if (this._dragging) {
  51217. // In case some browser do not support globalOut,
  51218. // and release mose out side the browser.
  51219. handleDragEnd.call(this, e);
  51220. }
  51221. else if (!e.target || !e.target.draggable) {
  51222. preventDefault(e);
  51223. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  51224. this._creatingCover = null;
  51225. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  51226. if (panel) {
  51227. this._dragging = true;
  51228. this._track = [localCursorPoint.slice()];
  51229. }
  51230. }
  51231. },
  51232. mousemove: function (e) {
  51233. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  51234. resetCursor(this, e, localCursorPoint);
  51235. if (this._dragging) {
  51236. preventDefault(e);
  51237. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  51238. eventParams && trigger$1(this, eventParams);
  51239. }
  51240. },
  51241. mouseup: handleDragEnd //,
  51242. // FIXME
  51243. // in tooltip, globalout should not be triggered.
  51244. // globalout: handleDragEnd
  51245. };
  51246. function handleDragEnd(e) {
  51247. if (this._dragging) {
  51248. preventDefault(e);
  51249. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  51250. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  51251. this._dragging = false;
  51252. this._track = [];
  51253. this._creatingCover = null;
  51254. // trigger event shoule be at final, after procedure will be nested.
  51255. eventParams && trigger$1(this, eventParams);
  51256. }
  51257. }
  51258. /**
  51259. * key: brushType
  51260. * @type {Object}
  51261. */
  51262. var coverRenderers = {
  51263. lineX: getLineRenderer(0),
  51264. lineY: getLineRenderer(1),
  51265. rect: {
  51266. createCover: function (controller, brushOption) {
  51267. return createBaseRectCover(
  51268. curry$2(
  51269. driftRect,
  51270. function (range) {
  51271. return range;
  51272. },
  51273. function (range) {
  51274. return range;
  51275. }
  51276. ),
  51277. controller,
  51278. brushOption,
  51279. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  51280. );
  51281. },
  51282. getCreatingRange: function (localTrack) {
  51283. var ends = getTrackEnds(localTrack);
  51284. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  51285. },
  51286. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51287. updateBaseRect(controller, cover, localRange, brushOption);
  51288. },
  51289. updateCommon: updateCommon,
  51290. contain: mainShapeContain
  51291. },
  51292. polygon: {
  51293. createCover: function (controller, brushOption) {
  51294. var cover = new Group();
  51295. // Do not use graphic.Polygon because graphic.Polyline do not close the
  51296. // border of the shape when drawing, which is a better experience for user.
  51297. cover.add(new Polyline({
  51298. name: 'main',
  51299. style: makeStyle(brushOption),
  51300. silent: true
  51301. }));
  51302. return cover;
  51303. },
  51304. getCreatingRange: function (localTrack) {
  51305. return localTrack;
  51306. },
  51307. endCreating: function (controller, cover) {
  51308. cover.remove(cover.childAt(0));
  51309. // Use graphic.Polygon close the shape.
  51310. cover.add(new Polygon({
  51311. name: 'main',
  51312. draggable: true,
  51313. drift: curry$2(driftPolygon, controller, cover),
  51314. ondragend: curry$2(trigger$1, controller, {isEnd: true})
  51315. }));
  51316. },
  51317. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51318. cover.childAt(0).setShape({
  51319. points: clipByPanel(controller, cover, localRange)
  51320. });
  51321. },
  51322. updateCommon: updateCommon,
  51323. contain: mainShapeContain
  51324. }
  51325. };
  51326. function getLineRenderer(xyIndex) {
  51327. return {
  51328. createCover: function (controller, brushOption) {
  51329. return createBaseRectCover(
  51330. curry$2(
  51331. driftRect,
  51332. function (range) {
  51333. var rectRange = [range, [0, 100]];
  51334. xyIndex && rectRange.reverse();
  51335. return rectRange;
  51336. },
  51337. function (rectRange) {
  51338. return rectRange[xyIndex];
  51339. }
  51340. ),
  51341. controller,
  51342. brushOption,
  51343. [['w', 'e'], ['n', 's']][xyIndex]
  51344. );
  51345. },
  51346. getCreatingRange: function (localTrack) {
  51347. var ends = getTrackEnds(localTrack);
  51348. var min = mathMin$6(ends[0][xyIndex], ends[1][xyIndex]);
  51349. var max = mathMax$6(ends[0][xyIndex], ends[1][xyIndex]);
  51350. return [min, max];
  51351. },
  51352. updateCoverShape: function (controller, cover, localRange, brushOption) {
  51353. var otherExtent;
  51354. // If brushWidth not specified, fit the panel.
  51355. var panel = getPanelByCover(controller, cover);
  51356. if (panel !== true && panel.getLinearBrushOtherExtent) {
  51357. otherExtent = panel.getLinearBrushOtherExtent(
  51358. xyIndex, controller._transform
  51359. );
  51360. }
  51361. else {
  51362. var zr = controller._zr;
  51363. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  51364. }
  51365. var rectRange = [localRange, otherExtent];
  51366. xyIndex && rectRange.reverse();
  51367. updateBaseRect(controller, cover, rectRange, brushOption);
  51368. },
  51369. updateCommon: updateCommon,
  51370. contain: mainShapeContain
  51371. };
  51372. }
  51373. /*
  51374. * Licensed to the Apache Software Foundation (ASF) under one
  51375. * or more contributor license agreements. See the NOTICE file
  51376. * distributed with this work for additional information
  51377. * regarding copyright ownership. The ASF licenses this file
  51378. * to you under the Apache License, Version 2.0 (the
  51379. * "License"); you may not use this file except in compliance
  51380. * with the License. You may obtain a copy of the License at
  51381. *
  51382. * http://www.apache.org/licenses/LICENSE-2.0
  51383. *
  51384. * Unless required by applicable law or agreed to in writing,
  51385. * software distributed under the License is distributed on an
  51386. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51387. * KIND, either express or implied. See the License for the
  51388. * specific language governing permissions and limitations
  51389. * under the License.
  51390. */
  51391. function makeRectPanelClipPath(rect) {
  51392. rect = normalizeRect(rect);
  51393. return function (localPoints, transform) {
  51394. return clipPointsByRect(localPoints, rect);
  51395. };
  51396. }
  51397. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  51398. rect = normalizeRect(rect);
  51399. return function (xyIndex) {
  51400. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  51401. var brushWidth = idx ? rect.width : rect.height;
  51402. var base = idx ? rect.x : rect.y;
  51403. return [base, base + (brushWidth || 0)];
  51404. };
  51405. }
  51406. function makeRectIsTargetByCursor(rect, api, targetModel) {
  51407. rect = normalizeRect(rect);
  51408. return function (e, localCursorPoint, transform) {
  51409. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  51410. && !onIrrelevantElement(e, api, targetModel);
  51411. };
  51412. }
  51413. // Consider width/height is negative.
  51414. function normalizeRect(rect) {
  51415. return BoundingRect.create(rect);
  51416. }
  51417. /*
  51418. * Licensed to the Apache Software Foundation (ASF) under one
  51419. * or more contributor license agreements. See the NOTICE file
  51420. * distributed with this work for additional information
  51421. * regarding copyright ownership. The ASF licenses this file
  51422. * to you under the Apache License, Version 2.0 (the
  51423. * "License"); you may not use this file except in compliance
  51424. * with the License. You may obtain a copy of the License at
  51425. *
  51426. * http://www.apache.org/licenses/LICENSE-2.0
  51427. *
  51428. * Unless required by applicable law or agreed to in writing,
  51429. * software distributed under the License is distributed on an
  51430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51431. * KIND, either express or implied. See the License for the
  51432. * specific language governing permissions and limitations
  51433. * under the License.
  51434. */
  51435. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  51436. var AxisView$2 = extendComponentView({
  51437. type: 'parallelAxis',
  51438. /**
  51439. * @override
  51440. */
  51441. init: function (ecModel, api) {
  51442. AxisView$2.superApply(this, 'init', arguments);
  51443. /**
  51444. * @type {module:echarts/component/helper/BrushController}
  51445. */
  51446. (this._brushController = new BrushController(api.getZr()))
  51447. .on('brush', bind(this._onBrush, this));
  51448. },
  51449. /**
  51450. * @override
  51451. */
  51452. render: function (axisModel, ecModel, api, payload) {
  51453. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  51454. return;
  51455. }
  51456. this.axisModel = axisModel;
  51457. this.api = api;
  51458. this.group.removeAll();
  51459. var oldAxisGroup = this._axisGroup;
  51460. this._axisGroup = new Group();
  51461. this.group.add(this._axisGroup);
  51462. if (!axisModel.get('show')) {
  51463. return;
  51464. }
  51465. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  51466. var coordSys = coordSysModel.coordinateSystem;
  51467. var areaSelectStyle = axisModel.getAreaSelectStyle();
  51468. var areaWidth = areaSelectStyle.width;
  51469. var dim = axisModel.axis.dim;
  51470. var axisLayout = coordSys.getAxisLayout(dim);
  51471. var builderOpt = extend(
  51472. {strokeContainThreshold: areaWidth},
  51473. axisLayout
  51474. );
  51475. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  51476. each$1(elementList, axisBuilder.add, axisBuilder);
  51477. this._axisGroup.add(axisBuilder.getGroup());
  51478. this._refreshBrushController(
  51479. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  51480. );
  51481. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  51482. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  51483. },
  51484. // /**
  51485. // * @override
  51486. // */
  51487. // updateVisual: function (axisModel, ecModel, api, payload) {
  51488. // this._brushController && this._brushController
  51489. // .updateCovers(getCoverInfoList(axisModel));
  51490. // },
  51491. _refreshBrushController: function (
  51492. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  51493. ) {
  51494. // After filtering, axis may change, select area needs to be update.
  51495. var extent = axisModel.axis.getExtent();
  51496. var extentLen = extent[1] - extent[0];
  51497. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  51498. // width/height might be negative, which will be
  51499. // normalized in BoundingRect.
  51500. var rect = BoundingRect.create({
  51501. x: extent[0],
  51502. y: -areaWidth / 2,
  51503. width: extentLen,
  51504. height: areaWidth
  51505. });
  51506. rect.x -= extra;
  51507. rect.width += 2 * extra;
  51508. this._brushController
  51509. .mount({
  51510. enableGlobalPan: true,
  51511. rotation: builderOpt.rotation,
  51512. position: builderOpt.position
  51513. })
  51514. .setPanels([{
  51515. panelId: 'pl',
  51516. clipPath: makeRectPanelClipPath(rect),
  51517. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  51518. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  51519. }])
  51520. .enableBrush({
  51521. brushType: 'lineX',
  51522. brushStyle: areaSelectStyle,
  51523. removeOnClick: true
  51524. })
  51525. .updateCovers(getCoverInfoList(axisModel));
  51526. },
  51527. _onBrush: function (coverInfoList, opt) {
  51528. // Do not cache these object, because the mey be changed.
  51529. var axisModel = this.axisModel;
  51530. var axis = axisModel.axis;
  51531. var intervals = map(coverInfoList, function (coverInfo) {
  51532. return [
  51533. axis.coordToData(coverInfo.range[0], true),
  51534. axis.coordToData(coverInfo.range[1], true)
  51535. ];
  51536. });
  51537. // If realtime is true, action is not dispatched on drag end, because
  51538. // the drag end emits the same params with the last drag move event,
  51539. // and may have some delay when using touch pad.
  51540. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  51541. this.api.dispatchAction({
  51542. type: 'axisAreaSelect',
  51543. parallelAxisId: axisModel.id,
  51544. intervals: intervals
  51545. });
  51546. }
  51547. },
  51548. /**
  51549. * @override
  51550. */
  51551. dispose: function () {
  51552. this._brushController.dispose();
  51553. }
  51554. });
  51555. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  51556. return payload
  51557. && payload.type === 'axisAreaSelect'
  51558. && ecModel.findComponents(
  51559. {mainType: 'parallelAxis', query: payload}
  51560. )[0] === axisModel;
  51561. }
  51562. function getCoverInfoList(axisModel) {
  51563. var axis = axisModel.axis;
  51564. return map(axisModel.activeIntervals, function (interval) {
  51565. return {
  51566. brushType: 'lineX',
  51567. panelId: 'pl',
  51568. range: [
  51569. axis.dataToCoord(interval[0], true),
  51570. axis.dataToCoord(interval[1], true)
  51571. ]
  51572. };
  51573. });
  51574. }
  51575. function getCoordSysModel(axisModel, ecModel) {
  51576. return ecModel.getComponent(
  51577. 'parallel', axisModel.get('parallelIndex')
  51578. );
  51579. }
  51580. /*
  51581. * Licensed to the Apache Software Foundation (ASF) under one
  51582. * or more contributor license agreements. See the NOTICE file
  51583. * distributed with this work for additional information
  51584. * regarding copyright ownership. The ASF licenses this file
  51585. * to you under the Apache License, Version 2.0 (the
  51586. * "License"); you may not use this file except in compliance
  51587. * with the License. You may obtain a copy of the License at
  51588. *
  51589. * http://www.apache.org/licenses/LICENSE-2.0
  51590. *
  51591. * Unless required by applicable law or agreed to in writing,
  51592. * software distributed under the License is distributed on an
  51593. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51594. * KIND, either express or implied. See the License for the
  51595. * specific language governing permissions and limitations
  51596. * under the License.
  51597. */
  51598. /*
  51599. * Licensed to the Apache Software Foundation (ASF) under one
  51600. * or more contributor license agreements. See the NOTICE file
  51601. * distributed with this work for additional information
  51602. * regarding copyright ownership. The ASF licenses this file
  51603. * to you under the Apache License, Version 2.0 (the
  51604. * "License"); you may not use this file except in compliance
  51605. * with the License. You may obtain a copy of the License at
  51606. *
  51607. * http://www.apache.org/licenses/LICENSE-2.0
  51608. *
  51609. * Unless required by applicable law or agreed to in writing,
  51610. * software distributed under the License is distributed on an
  51611. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51612. * KIND, either express or implied. See the License for the
  51613. * specific language governing permissions and limitations
  51614. * under the License.
  51615. */
  51616. var CLICK_THRESHOLD = 5; // > 4
  51617. // Parallel view
  51618. extendComponentView({
  51619. type: 'parallel',
  51620. render: function (parallelModel, ecModel, api) {
  51621. this._model = parallelModel;
  51622. this._api = api;
  51623. if (!this._handlers) {
  51624. this._handlers = {};
  51625. each$1(handlers, function (handler, eventName) {
  51626. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  51627. }, this);
  51628. }
  51629. createOrUpdate(
  51630. this,
  51631. '_throttledDispatchExpand',
  51632. parallelModel.get('axisExpandRate'),
  51633. 'fixRate'
  51634. );
  51635. },
  51636. dispose: function (ecModel, api) {
  51637. each$1(this._handlers, function (handler, eventName) {
  51638. api.getZr().off(eventName, handler);
  51639. });
  51640. this._handlers = null;
  51641. },
  51642. /**
  51643. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  51644. */
  51645. _throttledDispatchExpand: function (opt) {
  51646. this._dispatchExpand(opt);
  51647. },
  51648. _dispatchExpand: function (opt) {
  51649. opt && this._api.dispatchAction(
  51650. extend({type: 'parallelAxisExpand'}, opt)
  51651. );
  51652. }
  51653. });
  51654. var handlers = {
  51655. mousedown: function (e) {
  51656. if (checkTrigger(this, 'click')) {
  51657. this._mouseDownPoint = [e.offsetX, e.offsetY];
  51658. }
  51659. },
  51660. mouseup: function (e) {
  51661. var mouseDownPoint = this._mouseDownPoint;
  51662. if (checkTrigger(this, 'click') && mouseDownPoint) {
  51663. var point = [e.offsetX, e.offsetY];
  51664. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  51665. + Math.pow(mouseDownPoint[1] - point[1], 2);
  51666. if (dist > CLICK_THRESHOLD) {
  51667. return;
  51668. }
  51669. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  51670. [e.offsetX, e.offsetY]
  51671. );
  51672. result.behavior !== 'none' && this._dispatchExpand({
  51673. axisExpandWindow: result.axisExpandWindow
  51674. });
  51675. }
  51676. this._mouseDownPoint = null;
  51677. },
  51678. mousemove: function (e) {
  51679. // Should do nothing when brushing.
  51680. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  51681. return;
  51682. }
  51683. var model = this._model;
  51684. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  51685. [e.offsetX, e.offsetY]
  51686. );
  51687. var behavior = result.behavior;
  51688. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  51689. this._throttledDispatchExpand(
  51690. behavior === 'none'
  51691. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  51692. : {
  51693. axisExpandWindow: result.axisExpandWindow,
  51694. // Jumping uses animation, and sliding suppresses animation.
  51695. animation: behavior === 'jump' ? null : false
  51696. }
  51697. );
  51698. }
  51699. };
  51700. function checkTrigger(view, triggerOn) {
  51701. var model = view._model;
  51702. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  51703. }
  51704. registerPreprocessor(parallelPreprocessor);
  51705. /*
  51706. * Licensed to the Apache Software Foundation (ASF) under one
  51707. * or more contributor license agreements. See the NOTICE file
  51708. * distributed with this work for additional information
  51709. * regarding copyright ownership. The ASF licenses this file
  51710. * to you under the Apache License, Version 2.0 (the
  51711. * "License"); you may not use this file except in compliance
  51712. * with the License. You may obtain a copy of the License at
  51713. *
  51714. * http://www.apache.org/licenses/LICENSE-2.0
  51715. *
  51716. * Unless required by applicable law or agreed to in writing,
  51717. * software distributed under the License is distributed on an
  51718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51719. * KIND, either express or implied. See the License for the
  51720. * specific language governing permissions and limitations
  51721. * under the License.
  51722. */
  51723. SeriesModel.extend({
  51724. type: 'series.parallel',
  51725. dependencies: ['parallel'],
  51726. visualColorAccessPath: 'lineStyle.color',
  51727. getInitialData: function (option, ecModel) {
  51728. var source = this.getSource();
  51729. setEncodeAndDimensions(source, this);
  51730. return createListFromArray(source, this);
  51731. },
  51732. /**
  51733. * User can get data raw indices on 'axisAreaSelected' event received.
  51734. *
  51735. * @public
  51736. * @param {string} activeState 'active' or 'inactive' or 'normal'
  51737. * @return {Array.<number>} Raw indices
  51738. */
  51739. getRawIndicesByActiveState: function (activeState) {
  51740. var coordSys = this.coordinateSystem;
  51741. var data = this.getData();
  51742. var indices = [];
  51743. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  51744. if (activeState === theActiveState) {
  51745. indices.push(data.getRawIndex(dataIndex));
  51746. }
  51747. });
  51748. return indices;
  51749. },
  51750. defaultOption: {
  51751. zlevel: 0, // 一级层叠
  51752. z: 2, // 二级层叠
  51753. coordinateSystem: 'parallel',
  51754. parallelIndex: 0,
  51755. label: {
  51756. show: false
  51757. },
  51758. inactiveOpacity: 0.05,
  51759. activeOpacity: 1,
  51760. lineStyle: {
  51761. width: 1,
  51762. opacity: 0.45,
  51763. type: 'solid'
  51764. },
  51765. emphasis: {
  51766. label: {
  51767. show: false
  51768. }
  51769. },
  51770. progressive: 500,
  51771. smooth: false, // true | false | number
  51772. animationEasing: 'linear'
  51773. }
  51774. });
  51775. function setEncodeAndDimensions(source, seriesModel) {
  51776. // The mapping of parallelAxis dimension to data dimension can
  51777. // be specified in parallelAxis.option.dim. For example, if
  51778. // parallelAxis.option.dim is 'dim3', it mapping to the third
  51779. // dimension of data. But `data.encode` has higher priority.
  51780. // Moreover, parallelModel.dimension should not be regarded as data
  51781. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  51782. if (source.encodeDefine) {
  51783. return;
  51784. }
  51785. var parallelModel = seriesModel.ecModel.getComponent(
  51786. 'parallel', seriesModel.get('parallelIndex')
  51787. );
  51788. if (!parallelModel) {
  51789. return;
  51790. }
  51791. var encodeDefine = source.encodeDefine = createHashMap();
  51792. each$1(parallelModel.dimensions, function (axisDim) {
  51793. var dataDimIndex = convertDimNameToNumber(axisDim);
  51794. encodeDefine.set(axisDim, dataDimIndex);
  51795. });
  51796. }
  51797. function convertDimNameToNumber(dimName) {
  51798. return +dimName.replace('dim', '');
  51799. }
  51800. /*
  51801. * Licensed to the Apache Software Foundation (ASF) under one
  51802. * or more contributor license agreements. See the NOTICE file
  51803. * distributed with this work for additional information
  51804. * regarding copyright ownership. The ASF licenses this file
  51805. * to you under the Apache License, Version 2.0 (the
  51806. * "License"); you may not use this file except in compliance
  51807. * with the License. You may obtain a copy of the License at
  51808. *
  51809. * http://www.apache.org/licenses/LICENSE-2.0
  51810. *
  51811. * Unless required by applicable law or agreed to in writing,
  51812. * software distributed under the License is distributed on an
  51813. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51814. * KIND, either express or implied. See the License for the
  51815. * specific language governing permissions and limitations
  51816. * under the License.
  51817. */
  51818. var DEFAULT_SMOOTH = 0.3;
  51819. var ParallelView = Chart.extend({
  51820. type: 'parallel',
  51821. init: function () {
  51822. /**
  51823. * @type {module:zrender/container/Group}
  51824. * @private
  51825. */
  51826. this._dataGroup = new Group();
  51827. this.group.add(this._dataGroup);
  51828. /**
  51829. * @type {module:echarts/data/List}
  51830. */
  51831. this._data;
  51832. /**
  51833. * @type {boolean}
  51834. */
  51835. this._initialized;
  51836. },
  51837. /**
  51838. * @override
  51839. */
  51840. render: function (seriesModel, ecModel, api, payload) {
  51841. var dataGroup = this._dataGroup;
  51842. var data = seriesModel.getData();
  51843. var oldData = this._data;
  51844. var coordSys = seriesModel.coordinateSystem;
  51845. var dimensions = coordSys.dimensions;
  51846. var seriesScope = makeSeriesScope$2(seriesModel);
  51847. data.diff(oldData)
  51848. .add(add)
  51849. .update(update)
  51850. .remove(remove)
  51851. .execute();
  51852. function add(newDataIndex) {
  51853. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  51854. updateElCommon(line, data, newDataIndex, seriesScope);
  51855. }
  51856. function update(newDataIndex, oldDataIndex) {
  51857. var line = oldData.getItemGraphicEl(oldDataIndex);
  51858. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  51859. data.setItemGraphicEl(newDataIndex, line);
  51860. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  51861. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  51862. updateElCommon(line, data, newDataIndex, seriesScope);
  51863. }
  51864. function remove(oldDataIndex) {
  51865. var line = oldData.getItemGraphicEl(oldDataIndex);
  51866. dataGroup.remove(line);
  51867. }
  51868. // First create
  51869. if (!this._initialized) {
  51870. this._initialized = true;
  51871. var clipPath = createGridClipShape$1(
  51872. coordSys, seriesModel, function () {
  51873. // Callback will be invoked immediately if there is no animation
  51874. setTimeout(function () {
  51875. dataGroup.removeClipPath();
  51876. });
  51877. }
  51878. );
  51879. dataGroup.setClipPath(clipPath);
  51880. }
  51881. this._data = data;
  51882. },
  51883. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  51884. this._initialized = true;
  51885. this._data = null;
  51886. this._dataGroup.removeAll();
  51887. },
  51888. incrementalRender: function (taskParams, seriesModel, ecModel) {
  51889. var data = seriesModel.getData();
  51890. var coordSys = seriesModel.coordinateSystem;
  51891. var dimensions = coordSys.dimensions;
  51892. var seriesScope = makeSeriesScope$2(seriesModel);
  51893. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  51894. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  51895. line.incremental = true;
  51896. updateElCommon(line, data, dataIndex, seriesScope);
  51897. }
  51898. },
  51899. dispose: function () {},
  51900. // _renderForProgressive: function (seriesModel) {
  51901. // var dataGroup = this._dataGroup;
  51902. // var data = seriesModel.getData();
  51903. // var oldData = this._data;
  51904. // var coordSys = seriesModel.coordinateSystem;
  51905. // var dimensions = coordSys.dimensions;
  51906. // var option = seriesModel.option;
  51907. // var progressive = option.progressive;
  51908. // var smooth = option.smooth ? SMOOTH : null;
  51909. // // In progressive animation is disabled, so use simple data diff,
  51910. // // which effects performance less.
  51911. // // (Typically performance for data with length 7000+ like:
  51912. // // simpleDiff: 60ms, addEl: 184ms,
  51913. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  51914. // if (simpleDiff(oldData, data, dimensions)) {
  51915. // dataGroup.removeAll();
  51916. // data.each(function (dataIndex) {
  51917. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  51918. // });
  51919. // }
  51920. // updateElCommon(data, progressive, smooth);
  51921. // // Consider switch between progressive and not.
  51922. // data.__plProgressive = true;
  51923. // this._data = data;
  51924. // },
  51925. /**
  51926. * @override
  51927. */
  51928. remove: function () {
  51929. this._dataGroup && this._dataGroup.removeAll();
  51930. this._data = null;
  51931. }
  51932. });
  51933. function createGridClipShape$1(coordSys, seriesModel, cb) {
  51934. var parallelModel = coordSys.model;
  51935. var rect = coordSys.getRect();
  51936. var rectEl = new Rect({
  51937. shape: {
  51938. x: rect.x,
  51939. y: rect.y,
  51940. width: rect.width,
  51941. height: rect.height
  51942. }
  51943. });
  51944. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  51945. rectEl.setShape(dim, 0);
  51946. initProps(rectEl, {
  51947. shape: {
  51948. width: rect.width,
  51949. height: rect.height
  51950. }
  51951. }, seriesModel, cb);
  51952. return rectEl;
  51953. }
  51954. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  51955. var points = [];
  51956. for (var i = 0; i < dimensions.length; i++) {
  51957. var dimName = dimensions[i];
  51958. var value = data.get(data.mapDimension(dimName), dataIndex);
  51959. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  51960. points.push(coordSys.dataToPoint(value, dimName));
  51961. }
  51962. }
  51963. return points;
  51964. }
  51965. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  51966. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  51967. var line = new Polyline({
  51968. shape: {points: points},
  51969. silent: true,
  51970. z2: 10
  51971. });
  51972. dataGroup.add(line);
  51973. data.setItemGraphicEl(dataIndex, line);
  51974. return line;
  51975. }
  51976. function makeSeriesScope$2(seriesModel) {
  51977. var smooth = seriesModel.get('smooth', true);
  51978. smooth === true && (smooth = DEFAULT_SMOOTH);
  51979. return {
  51980. lineStyle: seriesModel.getModel('lineStyle').getLineStyle(),
  51981. smooth: smooth != null ? smooth : DEFAULT_SMOOTH
  51982. };
  51983. }
  51984. function updateElCommon(el, data, dataIndex, seriesScope) {
  51985. var lineStyle = seriesScope.lineStyle;
  51986. if (data.hasItemOption) {
  51987. var lineStyleModel = data.getItemModel(dataIndex).getModel('lineStyle');
  51988. lineStyle = lineStyleModel.getLineStyle();
  51989. }
  51990. el.useStyle(lineStyle);
  51991. var elStyle = el.style;
  51992. elStyle.fill = null;
  51993. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  51994. elStyle.stroke = data.getItemVisual(dataIndex, 'color');
  51995. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  51996. elStyle.opacity = data.getItemVisual(dataIndex, 'opacity');
  51997. seriesScope.smooth && (el.shape.smooth = seriesScope.smooth);
  51998. }
  51999. // function simpleDiff(oldData, newData, dimensions) {
  52000. // var oldLen;
  52001. // if (!oldData
  52002. // || !oldData.__plProgressive
  52003. // || (oldLen = oldData.count()) !== newData.count()
  52004. // ) {
  52005. // return true;
  52006. // }
  52007. // var dimLen = dimensions.length;
  52008. // for (var i = 0; i < oldLen; i++) {
  52009. // for (var j = 0; j < dimLen; j++) {
  52010. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  52011. // return true;
  52012. // }
  52013. // }
  52014. // }
  52015. // return false;
  52016. // }
  52017. // FIXME
  52018. // 公用方法?
  52019. function isEmptyValue(val, axisType) {
  52020. return axisType === 'category'
  52021. ? val == null
  52022. : (val == null || isNaN(val)); // axisType === 'value'
  52023. }
  52024. /*
  52025. * Licensed to the Apache Software Foundation (ASF) under one
  52026. * or more contributor license agreements. See the NOTICE file
  52027. * distributed with this work for additional information
  52028. * regarding copyright ownership. The ASF licenses this file
  52029. * to you under the Apache License, Version 2.0 (the
  52030. * "License"); you may not use this file except in compliance
  52031. * with the License. You may obtain a copy of the License at
  52032. *
  52033. * http://www.apache.org/licenses/LICENSE-2.0
  52034. *
  52035. * Unless required by applicable law or agreed to in writing,
  52036. * software distributed under the License is distributed on an
  52037. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52038. * KIND, either express or implied. See the License for the
  52039. * specific language governing permissions and limitations
  52040. * under the License.
  52041. */
  52042. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  52043. var parallelVisual = {
  52044. seriesType: 'parallel',
  52045. reset: function (seriesModel, ecModel, api) {
  52046. var itemStyleModel = seriesModel.getModel('itemStyle');
  52047. var lineStyleModel = seriesModel.getModel('lineStyle');
  52048. var globalColors = ecModel.get('color');
  52049. var color = lineStyleModel.get('color')
  52050. || itemStyleModel.get('color')
  52051. || globalColors[seriesModel.seriesIndex % globalColors.length];
  52052. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  52053. var activeOpacity = seriesModel.get('activeOpacity');
  52054. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  52055. var coordSys = seriesModel.coordinateSystem;
  52056. var data = seriesModel.getData();
  52057. var opacityMap = {
  52058. normal: lineStyle.opacity,
  52059. active: activeOpacity,
  52060. inactive: inactiveOpacity
  52061. };
  52062. data.setVisual('color', color);
  52063. function progress(params, data) {
  52064. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  52065. var opacity = opacityMap[activeState];
  52066. if (activeState === 'normal' && data.hasItemOption) {
  52067. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  52068. itemOpacity != null && (opacity = itemOpacity);
  52069. }
  52070. data.setItemVisual(dataIndex, 'opacity', opacity);
  52071. }, params.start, params.end);
  52072. }
  52073. return {progress: progress};
  52074. }
  52075. };
  52076. /*
  52077. * Licensed to the Apache Software Foundation (ASF) under one
  52078. * or more contributor license agreements. See the NOTICE file
  52079. * distributed with this work for additional information
  52080. * regarding copyright ownership. The ASF licenses this file
  52081. * to you under the Apache License, Version 2.0 (the
  52082. * "License"); you may not use this file except in compliance
  52083. * with the License. You may obtain a copy of the License at
  52084. *
  52085. * http://www.apache.org/licenses/LICENSE-2.0
  52086. *
  52087. * Unless required by applicable law or agreed to in writing,
  52088. * software distributed under the License is distributed on an
  52089. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52090. * KIND, either express or implied. See the License for the
  52091. * specific language governing permissions and limitations
  52092. * under the License.
  52093. */
  52094. registerVisual(parallelVisual);
  52095. /*
  52096. * Licensed to the Apache Software Foundation (ASF) under one
  52097. * or more contributor license agreements. See the NOTICE file
  52098. * distributed with this work for additional information
  52099. * regarding copyright ownership. The ASF licenses this file
  52100. * to you under the Apache License, Version 2.0 (the
  52101. * "License"); you may not use this file except in compliance
  52102. * with the License. You may obtain a copy of the License at
  52103. *
  52104. * http://www.apache.org/licenses/LICENSE-2.0
  52105. *
  52106. * Unless required by applicable law or agreed to in writing,
  52107. * software distributed under the License is distributed on an
  52108. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52109. * KIND, either express or implied. See the License for the
  52110. * specific language governing permissions and limitations
  52111. * under the License.
  52112. */
  52113. /**
  52114. * @file Get initial data and define sankey view's series model
  52115. * @author Deqing Li(annong035@gmail.com)
  52116. */
  52117. var SankeySeries = SeriesModel.extend({
  52118. type: 'series.sankey',
  52119. layoutInfo: null,
  52120. /**
  52121. * Init a graph data structure from data in option series
  52122. *
  52123. * @param {Object} option the object used to config echarts view
  52124. * @return {module:echarts/data/List} storage initial data
  52125. */
  52126. getInitialData: function (option) {
  52127. var links = option.edges || option.links;
  52128. var nodes = option.data || option.nodes;
  52129. if (nodes && links) {
  52130. var graph = createGraphFromNodeEdge(nodes, links, this, true);
  52131. return graph.data;
  52132. }
  52133. },
  52134. setNodePosition: function (dataIndex, localPosition) {
  52135. var dataItem = this.option.data[dataIndex];
  52136. dataItem.localX = localPosition[0];
  52137. dataItem.localY = localPosition[1];
  52138. },
  52139. /**
  52140. * Return the graphic data structure
  52141. *
  52142. * @return {module:echarts/data/Graph} graphic data structure
  52143. */
  52144. getGraph: function () {
  52145. return this.getData().graph;
  52146. },
  52147. /**
  52148. * Get edge data of graphic data structure
  52149. *
  52150. * @return {module:echarts/data/List} data structure of list
  52151. */
  52152. getEdgeData: function () {
  52153. return this.getGraph().edgeData;
  52154. },
  52155. /**
  52156. * @override
  52157. */
  52158. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  52159. // dataType === 'node' or empty do not show tooltip by default
  52160. if (dataType === 'edge') {
  52161. var params = this.getDataParams(dataIndex, dataType);
  52162. var rawDataOpt = params.data;
  52163. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  52164. if (params.value) {
  52165. html += ' : ' + params.value;
  52166. }
  52167. return encodeHTML(html);
  52168. }
  52169. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  52170. },
  52171. optionUpdated: function () {
  52172. var option = this.option;
  52173. if (option.focusNodeAdjacency === true) {
  52174. option.focusNodeAdjacency = 'allEdges';
  52175. }
  52176. },
  52177. defaultOption: {
  52178. zlevel: 0,
  52179. z: 2,
  52180. coordinateSystem: 'view',
  52181. layout: null,
  52182. // The position of the whole view
  52183. left: '5%',
  52184. top: '5%',
  52185. right: '20%',
  52186. bottom: '5%',
  52187. // Value can be 'vertical'
  52188. orient: 'horizontal',
  52189. // The dx of the node
  52190. nodeWidth: 20,
  52191. // The vertical distance between two nodes
  52192. nodeGap: 8,
  52193. // Control if the node can move or not
  52194. draggable: true,
  52195. // Value can be 'inEdges', 'outEdges', 'allEdges', true (the same as 'allEdges').
  52196. focusNodeAdjacency: false,
  52197. // The number of iterations to change the position of the node
  52198. layoutIterations: 32,
  52199. label: {
  52200. show: true,
  52201. position: 'right',
  52202. color: '#000',
  52203. fontSize: 12
  52204. },
  52205. itemStyle: {
  52206. borderWidth: 1,
  52207. borderColor: '#333'
  52208. },
  52209. lineStyle: {
  52210. color: '#314656',
  52211. opacity: 0.2,
  52212. curveness: 0.5
  52213. },
  52214. emphasis: {
  52215. label: {
  52216. show: true
  52217. },
  52218. lineStyle: {
  52219. opacity: 0.6
  52220. }
  52221. },
  52222. animationEasing: 'linear',
  52223. animationDuration: 1000
  52224. }
  52225. });
  52226. /*
  52227. * Licensed to the Apache Software Foundation (ASF) under one
  52228. * or more contributor license agreements. See the NOTICE file
  52229. * distributed with this work for additional information
  52230. * regarding copyright ownership. The ASF licenses this file
  52231. * to you under the Apache License, Version 2.0 (the
  52232. * "License"); you may not use this file except in compliance
  52233. * with the License. You may obtain a copy of the License at
  52234. *
  52235. * http://www.apache.org/licenses/LICENSE-2.0
  52236. *
  52237. * Unless required by applicable law or agreed to in writing,
  52238. * software distributed under the License is distributed on an
  52239. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52240. * KIND, either express or implied. See the License for the
  52241. * specific language governing permissions and limitations
  52242. * under the License.
  52243. */
  52244. /**
  52245. * @file The file used to draw sankey view
  52246. * @author Deqing Li(annong035@gmail.com)
  52247. */
  52248. var nodeOpacityPath$1 = ['itemStyle', 'opacity'];
  52249. var lineOpacityPath$1 = ['lineStyle', 'opacity'];
  52250. function getItemOpacity$1(item, opacityPath) {
  52251. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  52252. }
  52253. function fadeOutItem$1(item, opacityPath, opacityRatio) {
  52254. var el = item.getGraphicEl();
  52255. var opacity = getItemOpacity$1(item, opacityPath);
  52256. if (opacityRatio != null) {
  52257. opacity == null && (opacity = 1);
  52258. opacity *= opacityRatio;
  52259. }
  52260. el.downplay && el.downplay();
  52261. el.traverse(function (child) {
  52262. if (child.type !== 'group') {
  52263. child.setStyle('opacity', opacity);
  52264. }
  52265. });
  52266. }
  52267. function fadeInItem$1(item, opacityPath) {
  52268. var opacity = getItemOpacity$1(item, opacityPath);
  52269. var el = item.getGraphicEl();
  52270. el.highlight && el.highlight();
  52271. el.traverse(function (child) {
  52272. if (child.type !== 'group') {
  52273. child.setStyle('opacity', opacity);
  52274. }
  52275. });
  52276. }
  52277. var SankeyShape = extendShape({
  52278. shape: {
  52279. x1: 0, y1: 0,
  52280. x2: 0, y2: 0,
  52281. cpx1: 0, cpy1: 0,
  52282. cpx2: 0, cpy2: 0,
  52283. extent: 0,
  52284. orient: ''
  52285. },
  52286. buildPath: function (ctx, shape) {
  52287. var extent = shape.extent;
  52288. var orient = shape.orient;
  52289. if (orient === 'vertical') {
  52290. ctx.moveTo(shape.x1, shape.y1);
  52291. ctx.bezierCurveTo(
  52292. shape.cpx1, shape.cpy1,
  52293. shape.cpx2, shape.cpy2,
  52294. shape.x2, shape.y2
  52295. );
  52296. ctx.lineTo(shape.x2 + extent, shape.y2);
  52297. ctx.bezierCurveTo(
  52298. shape.cpx2 + extent, shape.cpy2,
  52299. shape.cpx1 + extent, shape.cpy1,
  52300. shape.x1 + extent, shape.y1
  52301. );
  52302. }
  52303. else {
  52304. ctx.moveTo(shape.x1, shape.y1);
  52305. ctx.bezierCurveTo(
  52306. shape.cpx1, shape.cpy1,
  52307. shape.cpx2, shape.cpy2,
  52308. shape.x2, shape.y2
  52309. );
  52310. ctx.lineTo(shape.x2, shape.y2 + extent);
  52311. ctx.bezierCurveTo(
  52312. shape.cpx2, shape.cpy2 + extent,
  52313. shape.cpx1, shape.cpy1 + extent,
  52314. shape.x1, shape.y1 + extent
  52315. );
  52316. }
  52317. ctx.closePath();
  52318. }
  52319. });
  52320. extendChartView({
  52321. type: 'sankey',
  52322. /**
  52323. * @private
  52324. * @type {module:echarts/chart/sankey/SankeySeries}
  52325. */
  52326. _model: null,
  52327. /**
  52328. * @private
  52329. * @type {boolean}
  52330. */
  52331. _focusAdjacencyDisabled: false,
  52332. render: function (seriesModel, ecModel, api) {
  52333. var sankeyView = this;
  52334. var graph = seriesModel.getGraph();
  52335. var group = this.group;
  52336. var layoutInfo = seriesModel.layoutInfo;
  52337. // view width
  52338. var width = layoutInfo.width;
  52339. // view height
  52340. var height = layoutInfo.height;
  52341. var nodeData = seriesModel.getData();
  52342. var edgeData = seriesModel.getData('edge');
  52343. var orient = seriesModel.get('orient');
  52344. this._model = seriesModel;
  52345. group.removeAll();
  52346. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  52347. // generate a bezire Curve for each edge
  52348. graph.eachEdge(function (edge) {
  52349. var curve = new SankeyShape();
  52350. curve.dataIndex = edge.dataIndex;
  52351. curve.seriesIndex = seriesModel.seriesIndex;
  52352. curve.dataType = 'edge';
  52353. var lineStyleModel = edge.getModel('lineStyle');
  52354. var curvature = lineStyleModel.get('curveness');
  52355. var n1Layout = edge.node1.getLayout();
  52356. var node1Model = edge.node1.getModel();
  52357. var dragX1 = node1Model.get('localX');
  52358. var dragY1 = node1Model.get('localY');
  52359. var n2Layout = edge.node2.getLayout();
  52360. var node2Model = edge.node2.getModel();
  52361. var dragX2 = node2Model.get('localX');
  52362. var dragY2 = node2Model.get('localY');
  52363. var edgeLayout = edge.getLayout();
  52364. var x1;
  52365. var y1;
  52366. var x2;
  52367. var y2;
  52368. var cpx1;
  52369. var cpy1;
  52370. var cpx2;
  52371. var cpy2;
  52372. curve.shape.extent = Math.max(1, edgeLayout.dy);
  52373. curve.shape.orient = orient;
  52374. if (orient === 'vertical') {
  52375. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + edgeLayout.sy;
  52376. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + n1Layout.dy;
  52377. x2 = (dragX2 != null ? dragX2 * width : n2Layout.x) + edgeLayout.ty;
  52378. y2 = dragY2 != null ? dragY2 * height : n2Layout.y;
  52379. cpx1 = x1;
  52380. cpy1 = y1 * (1 - curvature) + y2 * curvature;
  52381. cpx2 = x2;
  52382. cpy2 = y1 * curvature + y2 * (1 - curvature);
  52383. }
  52384. else {
  52385. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  52386. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy;
  52387. x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  52388. y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty;
  52389. cpx1 = x1 * (1 - curvature) + x2 * curvature;
  52390. cpy1 = y1;
  52391. cpx2 = x1 * curvature + x2 * (1 - curvature);
  52392. cpy2 = y2;
  52393. }
  52394. curve.setShape({
  52395. x1: x1,
  52396. y1: y1,
  52397. x2: x2,
  52398. y2: y2,
  52399. cpx1: cpx1,
  52400. cpy1: cpy1,
  52401. cpx2: cpx2,
  52402. cpy2: cpy2
  52403. });
  52404. curve.setStyle(lineStyleModel.getItemStyle());
  52405. // Special color, use source node color or target node color
  52406. switch (curve.style.fill) {
  52407. case 'source':
  52408. curve.style.fill = edge.node1.getVisual('color');
  52409. break;
  52410. case 'target':
  52411. curve.style.fill = edge.node2.getVisual('color');
  52412. break;
  52413. }
  52414. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  52415. group.add(curve);
  52416. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  52417. });
  52418. // Generate a rect for each node
  52419. graph.eachNode(function (node) {
  52420. var layout = node.getLayout();
  52421. var itemModel = node.getModel();
  52422. var dragX = itemModel.get('localX');
  52423. var dragY = itemModel.get('localY');
  52424. var labelModel = itemModel.getModel('label');
  52425. var labelHoverModel = itemModel.getModel('emphasis.label');
  52426. var rect = new Rect({
  52427. shape: {
  52428. x: dragX != null ? dragX * width : layout.x,
  52429. y: dragY != null ? dragY * height : layout.y,
  52430. width: layout.dx,
  52431. height: layout.dy
  52432. },
  52433. style: itemModel.getModel('itemStyle').getItemStyle()
  52434. });
  52435. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  52436. setLabelStyle(
  52437. rect.style, hoverStyle, labelModel, labelHoverModel,
  52438. {
  52439. labelFetcher: seriesModel,
  52440. labelDataIndex: node.dataIndex,
  52441. defaultText: node.id,
  52442. isRectText: true
  52443. }
  52444. );
  52445. rect.setStyle('fill', node.getVisual('color'));
  52446. setHoverStyle(rect, hoverStyle);
  52447. group.add(rect);
  52448. nodeData.setItemGraphicEl(node.dataIndex, rect);
  52449. rect.dataType = 'node';
  52450. });
  52451. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  52452. var itemModel = nodeData.getItemModel(dataIndex);
  52453. if (itemModel.get('draggable')) {
  52454. el.drift = function (dx, dy) {
  52455. sankeyView._focusAdjacencyDisabled = true;
  52456. this.shape.x += dx;
  52457. this.shape.y += dy;
  52458. this.dirty();
  52459. api.dispatchAction({
  52460. type: 'dragNode',
  52461. seriesId: seriesModel.id,
  52462. dataIndex: nodeData.getRawIndex(dataIndex),
  52463. localX: this.shape.x / width,
  52464. localY: this.shape.y / height
  52465. });
  52466. };
  52467. el.ondragend = function () {
  52468. sankeyView._focusAdjacencyDisabled = false;
  52469. };
  52470. el.draggable = true;
  52471. el.cursor = 'move';
  52472. }
  52473. if (itemModel.get('focusNodeAdjacency')) {
  52474. el.off('mouseover').on('mouseover', function () {
  52475. if (!sankeyView._focusAdjacencyDisabled) {
  52476. api.dispatchAction({
  52477. type: 'focusNodeAdjacency',
  52478. seriesId: seriesModel.id,
  52479. dataIndex: el.dataIndex
  52480. });
  52481. }
  52482. });
  52483. el.off('mouseout').on('mouseout', function () {
  52484. if (!sankeyView._focusAdjacencyDisabled) {
  52485. api.dispatchAction({
  52486. type: 'unfocusNodeAdjacency',
  52487. seriesId: seriesModel.id
  52488. });
  52489. }
  52490. });
  52491. }
  52492. });
  52493. edgeData.eachItemGraphicEl(function (el, dataIndex) {
  52494. var edgeModel = edgeData.getItemModel(dataIndex);
  52495. if (edgeModel.get('focusNodeAdjacency')) {
  52496. el.off('mouseover').on('mouseover', function () {
  52497. if (!sankeyView._focusAdjacencyDisabled) {
  52498. api.dispatchAction({
  52499. type: 'focusNodeAdjacency',
  52500. seriesId: seriesModel.id,
  52501. edgeDataIndex: el.dataIndex
  52502. });
  52503. }
  52504. });
  52505. el.off('mouseout').on('mouseout', function () {
  52506. if (!sankeyView._focusAdjacencyDisabled) {
  52507. api.dispatchAction({
  52508. type: 'unfocusNodeAdjacency',
  52509. seriesId: seriesModel.id
  52510. });
  52511. }
  52512. });
  52513. }
  52514. });
  52515. if (!this._data && seriesModel.get('animation')) {
  52516. group.setClipPath(createGridClipShape$2(group.getBoundingRect(), seriesModel, function () {
  52517. group.removeClipPath();
  52518. }));
  52519. }
  52520. this._data = seriesModel.getData();
  52521. },
  52522. dispose: function () {},
  52523. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  52524. var data = this._model.getData();
  52525. var graph = data.graph;
  52526. var dataIndex = payload.dataIndex;
  52527. var itemModel = data.getItemModel(dataIndex);
  52528. var edgeDataIndex = payload.edgeDataIndex;
  52529. if (dataIndex == null && edgeDataIndex == null) {
  52530. return;
  52531. }
  52532. var node = graph.getNodeByIndex(dataIndex);
  52533. var edge = graph.getEdgeByIndex(edgeDataIndex);
  52534. graph.eachNode(function (node) {
  52535. fadeOutItem$1(node, nodeOpacityPath$1, 0.1);
  52536. });
  52537. graph.eachEdge(function (edge) {
  52538. fadeOutItem$1(edge, lineOpacityPath$1, 0.1);
  52539. });
  52540. if (node) {
  52541. fadeInItem$1(node, nodeOpacityPath$1);
  52542. var focusNodeAdj = itemModel.get('focusNodeAdjacency');
  52543. if (focusNodeAdj === 'outEdges') {
  52544. each$1(node.outEdges, function (edge) {
  52545. if (edge.dataIndex < 0) {
  52546. return;
  52547. }
  52548. fadeInItem$1(edge, lineOpacityPath$1);
  52549. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  52550. });
  52551. }
  52552. else if (focusNodeAdj === 'inEdges') {
  52553. each$1(node.inEdges, function (edge) {
  52554. if (edge.dataIndex < 0) {
  52555. return;
  52556. }
  52557. fadeInItem$1(edge, lineOpacityPath$1);
  52558. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  52559. });
  52560. }
  52561. else if (focusNodeAdj === 'allEdges') {
  52562. each$1(node.edges, function (edge) {
  52563. if (edge.dataIndex < 0) {
  52564. return;
  52565. }
  52566. fadeInItem$1(edge, lineOpacityPath$1);
  52567. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  52568. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  52569. });
  52570. }
  52571. }
  52572. if (edge) {
  52573. fadeInItem$1(edge, lineOpacityPath$1);
  52574. fadeInItem$1(edge.node1, nodeOpacityPath$1);
  52575. fadeInItem$1(edge.node2, nodeOpacityPath$1);
  52576. }
  52577. },
  52578. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  52579. var graph = this._model.getGraph();
  52580. graph.eachNode(function (node) {
  52581. fadeOutItem$1(node, nodeOpacityPath$1);
  52582. });
  52583. graph.eachEdge(function (edge) {
  52584. fadeOutItem$1(edge, lineOpacityPath$1);
  52585. });
  52586. }
  52587. });
  52588. // Add animation to the view
  52589. function createGridClipShape$2(rect, seriesModel, cb) {
  52590. var rectEl = new Rect({
  52591. shape: {
  52592. x: rect.x - 10,
  52593. y: rect.y - 10,
  52594. width: 0,
  52595. height: rect.height + 20
  52596. }
  52597. });
  52598. initProps(rectEl, {
  52599. shape: {
  52600. width: rect.width + 20,
  52601. height: rect.height + 20
  52602. }
  52603. }, seriesModel, cb);
  52604. return rectEl;
  52605. }
  52606. /*
  52607. * Licensed to the Apache Software Foundation (ASF) under one
  52608. * or more contributor license agreements. See the NOTICE file
  52609. * distributed with this work for additional information
  52610. * regarding copyright ownership. The ASF licenses this file
  52611. * to you under the Apache License, Version 2.0 (the
  52612. * "License"); you may not use this file except in compliance
  52613. * with the License. You may obtain a copy of the License at
  52614. *
  52615. * http://www.apache.org/licenses/LICENSE-2.0
  52616. *
  52617. * Unless required by applicable law or agreed to in writing,
  52618. * software distributed under the License is distributed on an
  52619. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52620. * KIND, either express or implied. See the License for the
  52621. * specific language governing permissions and limitations
  52622. * under the License.
  52623. */
  52624. /**
  52625. * @file The interactive action of sankey view
  52626. * @author Deqing Li(annong035@gmail.com)
  52627. */
  52628. registerAction({
  52629. type: 'dragNode',
  52630. event: 'dragNode',
  52631. // here can only use 'update' now, other value is not support in echarts.
  52632. update: 'update'
  52633. }, function (payload, ecModel) {
  52634. ecModel.eachComponent({mainType: 'series', subType: 'sankey', query: payload}, function (seriesModel) {
  52635. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  52636. });
  52637. });
  52638. /*
  52639. * Licensed to the Apache Software Foundation (ASF) under one
  52640. * or more contributor license agreements. See the NOTICE file
  52641. * distributed with this work for additional information
  52642. * regarding copyright ownership. The ASF licenses this file
  52643. * to you under the Apache License, Version 2.0 (the
  52644. * "License"); you may not use this file except in compliance
  52645. * with the License. You may obtain a copy of the License at
  52646. *
  52647. * http://www.apache.org/licenses/LICENSE-2.0
  52648. *
  52649. * Unless required by applicable law or agreed to in writing,
  52650. * software distributed under the License is distributed on an
  52651. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52652. * KIND, either express or implied. See the License for the
  52653. * specific language governing permissions and limitations
  52654. * under the License.
  52655. */
  52656. /**
  52657. * @file The layout algorithm of sankey view
  52658. * @author Deqing Li(annong035@gmail.com)
  52659. */
  52660. var sankeyLayout = function (ecModel, api, payload) {
  52661. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  52662. var nodeWidth = seriesModel.get('nodeWidth');
  52663. var nodeGap = seriesModel.get('nodeGap');
  52664. var layoutInfo = getViewRect$3(seriesModel, api);
  52665. seriesModel.layoutInfo = layoutInfo;
  52666. var width = layoutInfo.width;
  52667. var height = layoutInfo.height;
  52668. var graph = seriesModel.getGraph();
  52669. var nodes = graph.nodes;
  52670. var edges = graph.edges;
  52671. computeNodeValues(nodes);
  52672. var filteredNodes = filter(nodes, function (node) {
  52673. return node.getLayout().value === 0;
  52674. });
  52675. var iterations = filteredNodes.length !== 0
  52676. ? 0 : seriesModel.get('layoutIterations');
  52677. var orient = seriesModel.get('orient');
  52678. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient);
  52679. });
  52680. };
  52681. /**
  52682. * Get the layout position of the whole view
  52683. *
  52684. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  52685. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  52686. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  52687. */
  52688. function getViewRect$3(seriesModel, api) {
  52689. return getLayoutRect(
  52690. seriesModel.getBoxLayoutParams(), {
  52691. width: api.getWidth(),
  52692. height: api.getHeight()
  52693. }
  52694. );
  52695. }
  52696. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient) {
  52697. computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient);
  52698. computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient);
  52699. computeEdgeDepths(nodes, orient);
  52700. }
  52701. /**
  52702. * Compute the value of each node by summing the associated edge's value
  52703. *
  52704. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52705. */
  52706. function computeNodeValues(nodes) {
  52707. each$1(nodes, function (node) {
  52708. var value1 = sum(node.outEdges, getEdgeValue);
  52709. var value2 = sum(node.inEdges, getEdgeValue);
  52710. var value = Math.max(value1, value2);
  52711. node.setLayout({value: value}, true);
  52712. });
  52713. }
  52714. /**
  52715. * Compute the x-position for each node.
  52716. *
  52717. * Here we use Kahn algorithm to detect cycle when we traverse
  52718. * the node to computer the initial x position.
  52719. *
  52720. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52721. * @param {number} nodeWidth the dx of the node
  52722. * @param {number} width the whole width of the area to draw the view
  52723. */
  52724. function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient) {
  52725. // Used to mark whether the edge is deleted. if it is deleted,
  52726. // the value is 0, otherwise it is 1.
  52727. var remainEdges = [];
  52728. // Storage each node's indegree.
  52729. var indegreeArr = [];
  52730. //Used to storage the node with indegree is equal to 0.
  52731. var zeroIndegrees = [];
  52732. var nextNode = [];
  52733. var x = 0;
  52734. var kx = 0;
  52735. for (var i = 0; i < edges.length; i++) {
  52736. remainEdges[i] = 1;
  52737. }
  52738. for (i = 0; i < nodes.length; i++) {
  52739. indegreeArr[i] = nodes[i].inEdges.length;
  52740. if (indegreeArr[i] === 0) {
  52741. zeroIndegrees.push(nodes[i]);
  52742. }
  52743. }
  52744. while (zeroIndegrees.length) {
  52745. for (var idx = 0; idx < zeroIndegrees.length; idx++) {
  52746. var node = zeroIndegrees[idx];
  52747. if (orient === 'vertical') {
  52748. node.setLayout({y: x}, true);
  52749. node.setLayout({dy: nodeWidth}, true);
  52750. }
  52751. else {
  52752. node.setLayout({x: x}, true);
  52753. node.setLayout({dx: nodeWidth}, true);
  52754. }
  52755. for (var oidx = 0; oidx < node.outEdges.length; oidx++) {
  52756. var edge = node.outEdges[oidx];
  52757. var indexEdge = edges.indexOf(edge);
  52758. remainEdges[indexEdge] = 0;
  52759. var targetNode = edge.node2;
  52760. var nodeIndex = nodes.indexOf(targetNode);
  52761. if (--indegreeArr[nodeIndex] === 0) {
  52762. nextNode.push(targetNode);
  52763. }
  52764. }
  52765. }
  52766. ++x;
  52767. zeroIndegrees = nextNode;
  52768. nextNode = [];
  52769. }
  52770. for (i = 0; i < remainEdges.length; i++) {
  52771. if (__DEV__) {
  52772. if (remainEdges[i] === 1) {
  52773. throw new Error('Sankey is a DAG, the original data has cycle!');
  52774. }
  52775. }
  52776. }
  52777. moveSinksRight(nodes, x, orient);
  52778. if (orient === 'vertical') {
  52779. kx = (height - nodeWidth) / (x - 1);
  52780. }
  52781. else {
  52782. kx = (width - nodeWidth) / (x - 1);
  52783. }
  52784. scaleNodeBreadths(nodes, kx, orient);
  52785. }
  52786. /**
  52787. * All the node without outEgdes are assigned maximum x-position and
  52788. * be aligned in the last column.
  52789. *
  52790. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52791. * @param {number} x value (x-1) use to assign to node without outEdges
  52792. * as x-position
  52793. */
  52794. function moveSinksRight(nodes, x, orient) {
  52795. each$1(nodes, function (node) {
  52796. if (!node.outEdges.length) {
  52797. if (orient === 'vertical') {
  52798. node.setLayout({y: x - 1}, true);
  52799. }
  52800. else {
  52801. node.setLayout({x: x - 1}, true);
  52802. }
  52803. }
  52804. });
  52805. }
  52806. /**
  52807. * Scale node x-position to the width
  52808. *
  52809. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52810. * @param {number} kx multiple used to scale nodes
  52811. */
  52812. function scaleNodeBreadths(nodes, kx, orient) {
  52813. each$1(nodes, function (node) {
  52814. if (orient === 'vertical') {
  52815. var nodeY = node.getLayout().y * kx;
  52816. node.setLayout({y: nodeY}, true);
  52817. }
  52818. else {
  52819. var nodeX = node.getLayout().x * kx;
  52820. node.setLayout({x: nodeX}, true);
  52821. }
  52822. });
  52823. }
  52824. /**
  52825. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  52826. *
  52827. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52828. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  52829. * @param {number} height the whole height of the area to draw the view
  52830. * @param {number} nodeGap the vertical distance between two nodes
  52831. * in the same column.
  52832. * @param {number} iterations the number of iterations for the algorithm
  52833. */
  52834. function computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient) {
  52835. var nodesByBreadth = prepareNodesByBreadth(nodes, orient);
  52836. initializeNodeDepth(nodes, nodesByBreadth, edges, height, width, nodeGap, orient);
  52837. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  52838. for (var alpha = 1; iterations > 0; iterations--) {
  52839. // 0.99 is a experience parameter, ensure that each iterations of
  52840. // changes as small as possible.
  52841. alpha *= 0.99;
  52842. relaxRightToLeft(nodesByBreadth, alpha, orient);
  52843. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  52844. relaxLeftToRight(nodesByBreadth, alpha, orient);
  52845. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  52846. }
  52847. }
  52848. function prepareNodesByBreadth(nodes, orient) {
  52849. var nodesByBreadth = [];
  52850. var keyAttr = orient === 'vertical' ? 'y' : 'x';
  52851. var groupResult = groupData(nodes, function (node) {
  52852. return node.getLayout()[keyAttr];
  52853. });
  52854. groupResult.keys.sort(function (a, b) {
  52855. return a - b;
  52856. });
  52857. each$1(groupResult.keys, function (key) {
  52858. nodesByBreadth.push(groupResult.buckets.get(key));
  52859. });
  52860. return nodesByBreadth;
  52861. }
  52862. /**
  52863. * Compute the original y-position for each node
  52864. *
  52865. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  52866. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  52867. * group by the array of all sankey nodes based on the nodes x-position.
  52868. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  52869. * @param {number} height the whole height of the area to draw the view
  52870. * @param {number} nodeGap the vertical distance between two nodes
  52871. */
  52872. function initializeNodeDepth(nodes, nodesByBreadth, edges, height, width, nodeGap, orient) {
  52873. var kyArray = [];
  52874. each$1(nodesByBreadth, function (nodes) {
  52875. var n = nodes.length;
  52876. var sum = 0;
  52877. var ky = 0;
  52878. each$1(nodes, function (node) {
  52879. sum += node.getLayout().value;
  52880. });
  52881. if (orient === 'vertical') {
  52882. ky = (width - (n - 1) * nodeGap) / sum;
  52883. }
  52884. else {
  52885. ky = (height - (n - 1) * nodeGap) / sum;
  52886. }
  52887. kyArray.push(ky);
  52888. });
  52889. kyArray.sort(function (a, b) {
  52890. return a - b;
  52891. });
  52892. var ky0 = kyArray[0];
  52893. each$1(nodesByBreadth, function (nodes) {
  52894. each$1(nodes, function (node, i) {
  52895. var nodeDy = node.getLayout().value * ky0;
  52896. if (orient === 'vertical') {
  52897. node.setLayout({x: i}, true);
  52898. node.setLayout({dx: nodeDy}, true);
  52899. }
  52900. else {
  52901. node.setLayout({y: i}, true);
  52902. node.setLayout({dy: nodeDy}, true);
  52903. }
  52904. });
  52905. });
  52906. each$1(edges, function (edge) {
  52907. var edgeDy = +edge.getValue() * ky0;
  52908. edge.setLayout({dy: edgeDy}, true);
  52909. });
  52910. }
  52911. /**
  52912. * Resolve the collision of initialized depth (y-position)
  52913. *
  52914. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  52915. * group by the array of all sankey nodes based on the nodes x-position.
  52916. * @param {number} nodeGap the vertical distance between two nodes
  52917. * @param {number} height the whole height of the area to draw the view
  52918. */
  52919. function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) {
  52920. each$1(nodesByBreadth, function (nodes) {
  52921. var node;
  52922. var dy;
  52923. var y0 = 0;
  52924. var n = nodes.length;
  52925. var i;
  52926. if (orient === 'vertical') {
  52927. var nodeX;
  52928. nodes.sort(function (a, b) {
  52929. return a.getLayout().x - b.getLayout().x;
  52930. });
  52931. for (i = 0; i < n; i++) {
  52932. node = nodes[i];
  52933. dy = y0 - node.getLayout().x;
  52934. if (dy > 0) {
  52935. nodeX = node.getLayout().x + dy;
  52936. node.setLayout({x: nodeX}, true);
  52937. }
  52938. y0 = node.getLayout().x + node.getLayout().dx + nodeGap;
  52939. }
  52940. // If the bottommost node goes outside the bounds, push it back up
  52941. dy = y0 - nodeGap - width;
  52942. if (dy > 0) {
  52943. nodeX = node.getLayout().x - dy;
  52944. node.setLayout({x: nodeX}, true);
  52945. y0 = nodeX;
  52946. for (i = n - 2; i >= 0; --i) {
  52947. node = nodes[i];
  52948. dy = node.getLayout().x + node.getLayout().dx + nodeGap - y0;
  52949. if (dy > 0) {
  52950. nodeX = node.getLayout().x - dy;
  52951. node.setLayout({x: nodeX}, true);
  52952. }
  52953. y0 = node.getLayout().x;
  52954. }
  52955. }
  52956. }
  52957. else {
  52958. var nodeY;
  52959. nodes.sort(function (a, b) {
  52960. return a.getLayout().y - b.getLayout().y;
  52961. });
  52962. for (i = 0; i < n; i++) {
  52963. node = nodes[i];
  52964. dy = y0 - node.getLayout().y;
  52965. if (dy > 0) {
  52966. nodeY = node.getLayout().y + dy;
  52967. node.setLayout({y: nodeY}, true);
  52968. }
  52969. y0 = node.getLayout().y + node.getLayout().dy + nodeGap;
  52970. }
  52971. // If the bottommost node goes outside the bounds, push it back up
  52972. dy = y0 - nodeGap - height;
  52973. if (dy > 0) {
  52974. nodeY = node.getLayout().y - dy;
  52975. node.setLayout({y: nodeY}, true);
  52976. y0 = nodeY;
  52977. for (i = n - 2; i >= 0; --i) {
  52978. node = nodes[i];
  52979. dy = node.getLayout().y + node.getLayout().dy + nodeGap - y0;
  52980. if (dy > 0) {
  52981. nodeY = node.getLayout().y - dy;
  52982. node.setLayout({y: nodeY}, true);
  52983. }
  52984. y0 = node.getLayout().y;
  52985. }
  52986. }
  52987. }
  52988. });
  52989. }
  52990. /**
  52991. * Change the y-position of the nodes, except most the right side nodes
  52992. *
  52993. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  52994. * group by the array of all sankey nodes based on the node x-position.
  52995. * @param {number} alpha parameter used to adjust the nodes y-position
  52996. */
  52997. function relaxRightToLeft(nodesByBreadth, alpha, orient) {
  52998. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  52999. each$1(nodes, function (node) {
  53000. if (node.outEdges.length) {
  53001. var y = sum(node.outEdges, weightedTarget, orient) / sum(node.outEdges, getEdgeValue, orient);
  53002. if (orient === 'vertical') {
  53003. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  53004. node.setLayout({x: nodeX}, true);
  53005. }
  53006. else {
  53007. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  53008. node.setLayout({y: nodeY}, true);
  53009. }
  53010. }
  53011. });
  53012. });
  53013. }
  53014. function weightedTarget(edge, orient) {
  53015. return center$1(edge.node2, orient) * edge.getValue();
  53016. }
  53017. function weightedSource(edge, orient) {
  53018. return center$1(edge.node1, orient) * edge.getValue();
  53019. }
  53020. function center$1(node, orient) {
  53021. if (orient === 'vertical') {
  53022. return node.getLayout().x + node.getLayout().dx / 2;
  53023. }
  53024. return node.getLayout().y + node.getLayout().dy / 2;
  53025. }
  53026. function getEdgeValue(edge) {
  53027. return edge.getValue();
  53028. }
  53029. function sum(array, f, orient) {
  53030. var sum = 0;
  53031. var len = array.length;
  53032. var i = -1;
  53033. while (++i < len) {
  53034. var value = +f.call(array, array[i], orient);
  53035. if (!isNaN(value)) {
  53036. sum += value;
  53037. }
  53038. }
  53039. return sum;
  53040. }
  53041. /**
  53042. * Change the y-position of the nodes, except most the left side nodes
  53043. *
  53044. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  53045. * group by the array of all sankey nodes based on the node x-position.
  53046. * @param {number} alpha parameter used to adjust the nodes y-position
  53047. */
  53048. function relaxLeftToRight(nodesByBreadth, alpha, orient) {
  53049. each$1(nodesByBreadth, function (nodes) {
  53050. each$1(nodes, function (node) {
  53051. if (node.inEdges.length) {
  53052. var y = sum(node.inEdges, weightedSource, orient) / sum(node.inEdges, getEdgeValue, orient);
  53053. if (orient === 'vertical') {
  53054. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  53055. node.setLayout({x: nodeX}, true);
  53056. }
  53057. else {
  53058. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  53059. node.setLayout({y: nodeY}, true);
  53060. }
  53061. }
  53062. });
  53063. });
  53064. }
  53065. /**
  53066. * Compute the depth(y-position) of each edge
  53067. *
  53068. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  53069. */
  53070. function computeEdgeDepths(nodes, orient) {
  53071. each$1(nodes, function (node) {
  53072. if (orient === 'vertical') {
  53073. node.outEdges.sort(function (a, b) {
  53074. return a.node2.getLayout().x - b.node2.getLayout().x;
  53075. });
  53076. node.inEdges.sort(function (a, b) {
  53077. return a.node1.getLayout().x - b.node1.getLayout().x;
  53078. });
  53079. }
  53080. else {
  53081. node.outEdges.sort(function (a, b) {
  53082. return a.node2.getLayout().y - b.node2.getLayout().y;
  53083. });
  53084. node.inEdges.sort(function (a, b) {
  53085. return a.node1.getLayout().y - b.node1.getLayout().y;
  53086. });
  53087. }
  53088. });
  53089. each$1(nodes, function (node) {
  53090. var sy = 0;
  53091. var ty = 0;
  53092. each$1(node.outEdges, function (edge) {
  53093. edge.setLayout({sy: sy}, true);
  53094. sy += edge.getLayout().dy;
  53095. });
  53096. each$1(node.inEdges, function (edge) {
  53097. edge.setLayout({ty: ty}, true);
  53098. ty += edge.getLayout().dy;
  53099. });
  53100. });
  53101. }
  53102. /*
  53103. * Licensed to the Apache Software Foundation (ASF) under one
  53104. * or more contributor license agreements. See the NOTICE file
  53105. * distributed with this work for additional information
  53106. * regarding copyright ownership. The ASF licenses this file
  53107. * to you under the Apache License, Version 2.0 (the
  53108. * "License"); you may not use this file except in compliance
  53109. * with the License. You may obtain a copy of the License at
  53110. *
  53111. * http://www.apache.org/licenses/LICENSE-2.0
  53112. *
  53113. * Unless required by applicable law or agreed to in writing,
  53114. * software distributed under the License is distributed on an
  53115. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53116. * KIND, either express or implied. See the License for the
  53117. * specific language governing permissions and limitations
  53118. * under the License.
  53119. */
  53120. /**
  53121. * @file Visual encoding for sankey view
  53122. * @author Deqing Li(annong035@gmail.com)
  53123. */
  53124. var sankeyVisual = function (ecModel, payload) {
  53125. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  53126. var graph = seriesModel.getGraph();
  53127. var nodes = graph.nodes;
  53128. if (nodes.length) {
  53129. var minValue = Infinity;
  53130. var maxValue = -Infinity;
  53131. each$1(nodes, function (node) {
  53132. var nodeValue = node.getLayout().value;
  53133. if (nodeValue < minValue) {
  53134. minValue = nodeValue;
  53135. }
  53136. if (nodeValue > maxValue) {
  53137. maxValue = nodeValue;
  53138. }
  53139. });
  53140. each$1(nodes, function (node) {
  53141. var mapping = new VisualMapping({
  53142. type: 'color',
  53143. mappingMethod: 'linear',
  53144. dataExtent: [minValue, maxValue],
  53145. visual: seriesModel.get('color')
  53146. });
  53147. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  53148. node.setVisual('color', mapValueToColor);
  53149. // If set itemStyle.normal.color
  53150. var itemModel = node.getModel();
  53151. var customColor = itemModel.get('itemStyle.color');
  53152. if (customColor != null) {
  53153. node.setVisual('color', customColor);
  53154. }
  53155. });
  53156. }
  53157. });
  53158. };
  53159. /*
  53160. * Licensed to the Apache Software Foundation (ASF) under one
  53161. * or more contributor license agreements. See the NOTICE file
  53162. * distributed with this work for additional information
  53163. * regarding copyright ownership. The ASF licenses this file
  53164. * to you under the Apache License, Version 2.0 (the
  53165. * "License"); you may not use this file except in compliance
  53166. * with the License. You may obtain a copy of the License at
  53167. *
  53168. * http://www.apache.org/licenses/LICENSE-2.0
  53169. *
  53170. * Unless required by applicable law or agreed to in writing,
  53171. * software distributed under the License is distributed on an
  53172. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53173. * KIND, either express or implied. See the License for the
  53174. * specific language governing permissions and limitations
  53175. * under the License.
  53176. */
  53177. registerLayout(sankeyLayout);
  53178. registerVisual(sankeyVisual);
  53179. /*
  53180. * Licensed to the Apache Software Foundation (ASF) under one
  53181. * or more contributor license agreements. See the NOTICE file
  53182. * distributed with this work for additional information
  53183. * regarding copyright ownership. The ASF licenses this file
  53184. * to you under the Apache License, Version 2.0 (the
  53185. * "License"); you may not use this file except in compliance
  53186. * with the License. You may obtain a copy of the License at
  53187. *
  53188. * http://www.apache.org/licenses/LICENSE-2.0
  53189. *
  53190. * Unless required by applicable law or agreed to in writing,
  53191. * software distributed under the License is distributed on an
  53192. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53193. * KIND, either express or implied. See the License for the
  53194. * specific language governing permissions and limitations
  53195. * under the License.
  53196. */
  53197. var seriesModelMixin = {
  53198. /**
  53199. * @private
  53200. * @type {string}
  53201. */
  53202. _baseAxisDim: null,
  53203. /**
  53204. * @override
  53205. */
  53206. getInitialData: function (option, ecModel) {
  53207. // When both types of xAxis and yAxis are 'value', layout is
  53208. // needed to be specified by user. Otherwise, layout can be
  53209. // judged by which axis is category.
  53210. var ordinalMeta;
  53211. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  53212. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  53213. var xAxisType = xAxisModel.get('type');
  53214. var yAxisType = yAxisModel.get('type');
  53215. var addOrdinal;
  53216. // FIXME
  53217. // 考虑时间轴
  53218. if (xAxisType === 'category') {
  53219. option.layout = 'horizontal';
  53220. ordinalMeta = xAxisModel.getOrdinalMeta();
  53221. addOrdinal = true;
  53222. }
  53223. else if (yAxisType === 'category') {
  53224. option.layout = 'vertical';
  53225. ordinalMeta = yAxisModel.getOrdinalMeta();
  53226. addOrdinal = true;
  53227. }
  53228. else {
  53229. option.layout = option.layout || 'horizontal';
  53230. }
  53231. var coordDims = ['x', 'y'];
  53232. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  53233. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  53234. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  53235. var axisModels = [xAxisModel, yAxisModel];
  53236. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  53237. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  53238. var data = option.data;
  53239. // ??? FIXME make a stage to perform data transfrom.
  53240. // MUST create a new data, consider setOption({}) again.
  53241. if (data && addOrdinal) {
  53242. var newOptionData = [];
  53243. each$1(data, function (item, index) {
  53244. var newItem;
  53245. if (item.value && isArray(item.value)) {
  53246. newItem = item.value.slice();
  53247. item.value.unshift(index);
  53248. }
  53249. else if (isArray(item)) {
  53250. newItem = item.slice();
  53251. item.unshift(index);
  53252. }
  53253. else {
  53254. newItem = item;
  53255. }
  53256. newOptionData.push(newItem);
  53257. });
  53258. option.data = newOptionData;
  53259. }
  53260. var defaultValueDimensions = this.defaultValueDimensions;
  53261. return createListSimply(
  53262. this,
  53263. {
  53264. coordDimensions: [{
  53265. name: baseAxisDim,
  53266. type: getDimensionTypeByAxis(baseAxisType),
  53267. ordinalMeta: ordinalMeta,
  53268. otherDims: {
  53269. tooltip: false,
  53270. itemName: 0
  53271. },
  53272. dimsDef: ['base']
  53273. }, {
  53274. name: otherAxisDim,
  53275. type: getDimensionTypeByAxis(otherAxisType),
  53276. dimsDef: defaultValueDimensions.slice()
  53277. }],
  53278. dimensionsCount: defaultValueDimensions.length + 1
  53279. }
  53280. );
  53281. },
  53282. /**
  53283. * If horizontal, base axis is x, otherwise y.
  53284. * @override
  53285. */
  53286. getBaseAxis: function () {
  53287. var dim = this._baseAxisDim;
  53288. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  53289. }
  53290. };
  53291. /*
  53292. * Licensed to the Apache Software Foundation (ASF) under one
  53293. * or more contributor license agreements. See the NOTICE file
  53294. * distributed with this work for additional information
  53295. * regarding copyright ownership. The ASF licenses this file
  53296. * to you under the Apache License, Version 2.0 (the
  53297. * "License"); you may not use this file except in compliance
  53298. * with the License. You may obtain a copy of the License at
  53299. *
  53300. * http://www.apache.org/licenses/LICENSE-2.0
  53301. *
  53302. * Unless required by applicable law or agreed to in writing,
  53303. * software distributed under the License is distributed on an
  53304. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53305. * KIND, either express or implied. See the License for the
  53306. * specific language governing permissions and limitations
  53307. * under the License.
  53308. */
  53309. var BoxplotSeries = SeriesModel.extend({
  53310. type: 'series.boxplot',
  53311. dependencies: ['xAxis', 'yAxis', 'grid'],
  53312. // TODO
  53313. // box width represents group size, so dimension should have 'size'.
  53314. /**
  53315. * @see <https://en.wikipedia.org/wiki/Box_plot>
  53316. * The meanings of 'min' and 'max' depend on user,
  53317. * and echarts do not need to know it.
  53318. * @readOnly
  53319. */
  53320. defaultValueDimensions: [
  53321. {name: 'min', defaultTooltip: true},
  53322. {name: 'Q1', defaultTooltip: true},
  53323. {name: 'median', defaultTooltip: true},
  53324. {name: 'Q3', defaultTooltip: true},
  53325. {name: 'max', defaultTooltip: true}
  53326. ],
  53327. /**
  53328. * @type {Array.<string>}
  53329. * @readOnly
  53330. */
  53331. dimensions: null,
  53332. /**
  53333. * @override
  53334. */
  53335. defaultOption: {
  53336. zlevel: 0, // 一级层叠
  53337. z: 2, // 二级层叠
  53338. coordinateSystem: 'cartesian2d',
  53339. legendHoverLink: true,
  53340. hoverAnimation: true,
  53341. // xAxisIndex: 0,
  53342. // yAxisIndex: 0,
  53343. layout: null, // 'horizontal' or 'vertical'
  53344. boxWidth: [7, 50], // [min, max] can be percent of band width.
  53345. itemStyle: {
  53346. color: '#fff',
  53347. borderWidth: 1
  53348. },
  53349. emphasis: {
  53350. itemStyle: {
  53351. borderWidth: 2,
  53352. shadowBlur: 5,
  53353. shadowOffsetX: 2,
  53354. shadowOffsetY: 2,
  53355. shadowColor: 'rgba(0,0,0,0.4)'
  53356. }
  53357. },
  53358. animationEasing: 'elasticOut',
  53359. animationDuration: 800
  53360. }
  53361. });
  53362. mixin(BoxplotSeries, seriesModelMixin, true);
  53363. /*
  53364. * Licensed to the Apache Software Foundation (ASF) under one
  53365. * or more contributor license agreements. See the NOTICE file
  53366. * distributed with this work for additional information
  53367. * regarding copyright ownership. The ASF licenses this file
  53368. * to you under the Apache License, Version 2.0 (the
  53369. * "License"); you may not use this file except in compliance
  53370. * with the License. You may obtain a copy of the License at
  53371. *
  53372. * http://www.apache.org/licenses/LICENSE-2.0
  53373. *
  53374. * Unless required by applicable law or agreed to in writing,
  53375. * software distributed under the License is distributed on an
  53376. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53377. * KIND, either express or implied. See the License for the
  53378. * specific language governing permissions and limitations
  53379. * under the License.
  53380. */
  53381. // Update common properties
  53382. var NORMAL_ITEM_STYLE_PATH = ['itemStyle'];
  53383. var EMPHASIS_ITEM_STYLE_PATH = ['emphasis', 'itemStyle'];
  53384. var BoxplotView = Chart.extend({
  53385. type: 'boxplot',
  53386. render: function (seriesModel, ecModel, api) {
  53387. var data = seriesModel.getData();
  53388. var group = this.group;
  53389. var oldData = this._data;
  53390. // There is no old data only when first rendering or switching from
  53391. // stream mode to normal mode, where previous elements should be removed.
  53392. if (!this._data) {
  53393. group.removeAll();
  53394. }
  53395. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  53396. data.diff(oldData)
  53397. .add(function (newIdx) {
  53398. if (data.hasValue(newIdx)) {
  53399. var itemLayout = data.getItemLayout(newIdx);
  53400. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  53401. data.setItemGraphicEl(newIdx, symbolEl);
  53402. group.add(symbolEl);
  53403. }
  53404. })
  53405. .update(function (newIdx, oldIdx) {
  53406. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  53407. // Empty data
  53408. if (!data.hasValue(newIdx)) {
  53409. group.remove(symbolEl);
  53410. return;
  53411. }
  53412. var itemLayout = data.getItemLayout(newIdx);
  53413. if (!symbolEl) {
  53414. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  53415. }
  53416. else {
  53417. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  53418. }
  53419. group.add(symbolEl);
  53420. data.setItemGraphicEl(newIdx, symbolEl);
  53421. })
  53422. .remove(function (oldIdx) {
  53423. var el = oldData.getItemGraphicEl(oldIdx);
  53424. el && group.remove(el);
  53425. })
  53426. .execute();
  53427. this._data = data;
  53428. },
  53429. remove: function (ecModel) {
  53430. var group = this.group;
  53431. var data = this._data;
  53432. this._data = null;
  53433. data && data.eachItemGraphicEl(function (el) {
  53434. el && group.remove(el);
  53435. });
  53436. },
  53437. dispose: noop
  53438. });
  53439. var BoxPath = Path.extend({
  53440. type: 'boxplotBoxPath',
  53441. shape: {},
  53442. buildPath: function (ctx, shape) {
  53443. var ends = shape.points;
  53444. var i = 0;
  53445. ctx.moveTo(ends[i][0], ends[i][1]);
  53446. i++;
  53447. for (; i < 4; i++) {
  53448. ctx.lineTo(ends[i][0], ends[i][1]);
  53449. }
  53450. ctx.closePath();
  53451. for (; i < ends.length; i++) {
  53452. ctx.moveTo(ends[i][0], ends[i][1]);
  53453. i++;
  53454. ctx.lineTo(ends[i][0], ends[i][1]);
  53455. }
  53456. }
  53457. });
  53458. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  53459. var ends = itemLayout.ends;
  53460. var el = new BoxPath({
  53461. shape: {
  53462. points: isInit
  53463. ? transInit(ends, constDim, itemLayout)
  53464. : ends
  53465. }
  53466. });
  53467. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  53468. return el;
  53469. }
  53470. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  53471. var seriesModel = data.hostModel;
  53472. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  53473. updateMethod(
  53474. el,
  53475. {shape: {points: itemLayout.ends}},
  53476. seriesModel,
  53477. dataIndex
  53478. );
  53479. var itemModel = data.getItemModel(dataIndex);
  53480. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH);
  53481. var borderColor = data.getItemVisual(dataIndex, 'color');
  53482. // Exclude borderColor.
  53483. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  53484. itemStyle.stroke = borderColor;
  53485. itemStyle.strokeNoScale = true;
  53486. el.useStyle(itemStyle);
  53487. el.z2 = 100;
  53488. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH).getItemStyle();
  53489. setHoverStyle(el, hoverStyle);
  53490. }
  53491. function transInit(points, dim, itemLayout) {
  53492. return map(points, function (point) {
  53493. point = point.slice();
  53494. point[dim] = itemLayout.initBaseline;
  53495. return point;
  53496. });
  53497. }
  53498. /*
  53499. * Licensed to the Apache Software Foundation (ASF) under one
  53500. * or more contributor license agreements. See the NOTICE file
  53501. * distributed with this work for additional information
  53502. * regarding copyright ownership. The ASF licenses this file
  53503. * to you under the Apache License, Version 2.0 (the
  53504. * "License"); you may not use this file except in compliance
  53505. * with the License. You may obtain a copy of the License at
  53506. *
  53507. * http://www.apache.org/licenses/LICENSE-2.0
  53508. *
  53509. * Unless required by applicable law or agreed to in writing,
  53510. * software distributed under the License is distributed on an
  53511. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53512. * KIND, either express or implied. See the License for the
  53513. * specific language governing permissions and limitations
  53514. * under the License.
  53515. */
  53516. var borderColorQuery = ['itemStyle', 'borderColor'];
  53517. var boxplotVisual = function (ecModel, api) {
  53518. var globalColors = ecModel.get('color');
  53519. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  53520. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  53521. var data = seriesModel.getData();
  53522. data.setVisual({
  53523. legendSymbol: 'roundRect',
  53524. // Use name 'color' but not 'borderColor' for legend usage and
  53525. // visual coding from other component like dataRange.
  53526. color: seriesModel.get(borderColorQuery) || defaulColor
  53527. });
  53528. // Only visible series has each data be visual encoded
  53529. if (!ecModel.isSeriesFiltered(seriesModel)) {
  53530. data.each(function (idx) {
  53531. var itemModel = data.getItemModel(idx);
  53532. data.setItemVisual(
  53533. idx,
  53534. {color: itemModel.get(borderColorQuery, true)}
  53535. );
  53536. });
  53537. }
  53538. });
  53539. };
  53540. /*
  53541. * Licensed to the Apache Software Foundation (ASF) under one
  53542. * or more contributor license agreements. See the NOTICE file
  53543. * distributed with this work for additional information
  53544. * regarding copyright ownership. The ASF licenses this file
  53545. * to you under the Apache License, Version 2.0 (the
  53546. * "License"); you may not use this file except in compliance
  53547. * with the License. You may obtain a copy of the License at
  53548. *
  53549. * http://www.apache.org/licenses/LICENSE-2.0
  53550. *
  53551. * Unless required by applicable law or agreed to in writing,
  53552. * software distributed under the License is distributed on an
  53553. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53554. * KIND, either express or implied. See the License for the
  53555. * specific language governing permissions and limitations
  53556. * under the License.
  53557. */
  53558. var each$13 = each$1;
  53559. var boxplotLayout = function (ecModel) {
  53560. var groupResult = groupSeriesByAxis(ecModel);
  53561. each$13(groupResult, function (groupItem) {
  53562. var seriesModels = groupItem.seriesModels;
  53563. if (!seriesModels.length) {
  53564. return;
  53565. }
  53566. calculateBase(groupItem);
  53567. each$13(seriesModels, function (seriesModel, idx) {
  53568. layoutSingleSeries(
  53569. seriesModel,
  53570. groupItem.boxOffsetList[idx],
  53571. groupItem.boxWidthList[idx]
  53572. );
  53573. });
  53574. });
  53575. };
  53576. /**
  53577. * Group series by axis.
  53578. */
  53579. function groupSeriesByAxis(ecModel) {
  53580. var result = [];
  53581. var axisList = [];
  53582. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  53583. var baseAxis = seriesModel.getBaseAxis();
  53584. var idx = indexOf(axisList, baseAxis);
  53585. if (idx < 0) {
  53586. idx = axisList.length;
  53587. axisList[idx] = baseAxis;
  53588. result[idx] = {axis: baseAxis, seriesModels: []};
  53589. }
  53590. result[idx].seriesModels.push(seriesModel);
  53591. });
  53592. return result;
  53593. }
  53594. /**
  53595. * Calculate offset and box width for each series.
  53596. */
  53597. function calculateBase(groupItem) {
  53598. var extent;
  53599. var baseAxis = groupItem.axis;
  53600. var seriesModels = groupItem.seriesModels;
  53601. var seriesCount = seriesModels.length;
  53602. var boxWidthList = groupItem.boxWidthList = [];
  53603. var boxOffsetList = groupItem.boxOffsetList = [];
  53604. var boundList = [];
  53605. var bandWidth;
  53606. if (baseAxis.type === 'category') {
  53607. bandWidth = baseAxis.getBandWidth();
  53608. }
  53609. else {
  53610. var maxDataCount = 0;
  53611. each$13(seriesModels, function (seriesModel) {
  53612. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  53613. });
  53614. extent = baseAxis.getExtent(),
  53615. Math.abs(extent[1] - extent[0]) / maxDataCount;
  53616. }
  53617. each$13(seriesModels, function (seriesModel) {
  53618. var boxWidthBound = seriesModel.get('boxWidth');
  53619. if (!isArray(boxWidthBound)) {
  53620. boxWidthBound = [boxWidthBound, boxWidthBound];
  53621. }
  53622. boundList.push([
  53623. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  53624. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  53625. ]);
  53626. });
  53627. var availableWidth = bandWidth * 0.8 - 2;
  53628. var boxGap = availableWidth / seriesCount * 0.3;
  53629. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  53630. var base = boxWidth / 2 - availableWidth / 2;
  53631. each$13(seriesModels, function (seriesModel, idx) {
  53632. boxOffsetList.push(base);
  53633. base += boxGap + boxWidth;
  53634. boxWidthList.push(
  53635. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  53636. );
  53637. });
  53638. }
  53639. /**
  53640. * Calculate points location for each series.
  53641. */
  53642. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  53643. var coordSys = seriesModel.coordinateSystem;
  53644. var data = seriesModel.getData();
  53645. var halfWidth = boxWidth / 2;
  53646. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  53647. var vDimIdx = 1 - cDimIdx;
  53648. var coordDims = ['x', 'y'];
  53649. var cDim = data.mapDimension(coordDims[cDimIdx]);
  53650. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  53651. if (cDim == null || vDims.length < 5) {
  53652. return;
  53653. }
  53654. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  53655. var axisDimVal = data.get(cDim, dataIndex);
  53656. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  53657. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  53658. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  53659. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  53660. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  53661. var ends = [];
  53662. addBodyEnd(ends, end2, 0);
  53663. addBodyEnd(ends, end4, 1);
  53664. ends.push(end1, end2, end5, end4);
  53665. layEndLine(ends, end1);
  53666. layEndLine(ends, end5);
  53667. layEndLine(ends, median);
  53668. data.setItemLayout(dataIndex, {
  53669. initBaseline: median[vDimIdx],
  53670. ends: ends
  53671. });
  53672. }
  53673. function getPoint(axisDimVal, dimIdx, dataIndex) {
  53674. var val = data.get(dimIdx, dataIndex);
  53675. var p = [];
  53676. p[cDimIdx] = axisDimVal;
  53677. p[vDimIdx] = val;
  53678. var point;
  53679. if (isNaN(axisDimVal) || isNaN(val)) {
  53680. point = [NaN, NaN];
  53681. }
  53682. else {
  53683. point = coordSys.dataToPoint(p);
  53684. point[cDimIdx] += offset;
  53685. }
  53686. return point;
  53687. }
  53688. function addBodyEnd(ends, point, start) {
  53689. var point1 = point.slice();
  53690. var point2 = point.slice();
  53691. point1[cDimIdx] += halfWidth;
  53692. point2[cDimIdx] -= halfWidth;
  53693. start
  53694. ? ends.push(point1, point2)
  53695. : ends.push(point2, point1);
  53696. }
  53697. function layEndLine(ends, endCenter) {
  53698. var from = endCenter.slice();
  53699. var to = endCenter.slice();
  53700. from[cDimIdx] -= halfWidth;
  53701. to[cDimIdx] += halfWidth;
  53702. ends.push(from, to);
  53703. }
  53704. }
  53705. /*
  53706. * Licensed to the Apache Software Foundation (ASF) under one
  53707. * or more contributor license agreements. See the NOTICE file
  53708. * distributed with this work for additional information
  53709. * regarding copyright ownership. The ASF licenses this file
  53710. * to you under the Apache License, Version 2.0 (the
  53711. * "License"); you may not use this file except in compliance
  53712. * with the License. You may obtain a copy of the License at
  53713. *
  53714. * http://www.apache.org/licenses/LICENSE-2.0
  53715. *
  53716. * Unless required by applicable law or agreed to in writing,
  53717. * software distributed under the License is distributed on an
  53718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53719. * KIND, either express or implied. See the License for the
  53720. * specific language governing permissions and limitations
  53721. * under the License.
  53722. */
  53723. registerVisual(boxplotVisual);
  53724. registerLayout(boxplotLayout);
  53725. /*
  53726. * Licensed to the Apache Software Foundation (ASF) under one
  53727. * or more contributor license agreements. See the NOTICE file
  53728. * distributed with this work for additional information
  53729. * regarding copyright ownership. The ASF licenses this file
  53730. * to you under the Apache License, Version 2.0 (the
  53731. * "License"); you may not use this file except in compliance
  53732. * with the License. You may obtain a copy of the License at
  53733. *
  53734. * http://www.apache.org/licenses/LICENSE-2.0
  53735. *
  53736. * Unless required by applicable law or agreed to in writing,
  53737. * software distributed under the License is distributed on an
  53738. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53739. * KIND, either express or implied. See the License for the
  53740. * specific language governing permissions and limitations
  53741. * under the License.
  53742. */
  53743. var CandlestickSeries = SeriesModel.extend({
  53744. type: 'series.candlestick',
  53745. dependencies: ['xAxis', 'yAxis', 'grid'],
  53746. /**
  53747. * @readOnly
  53748. */
  53749. defaultValueDimensions: [
  53750. {name: 'open', defaultTooltip: true},
  53751. {name: 'close', defaultTooltip: true},
  53752. {name: 'lowest', defaultTooltip: true},
  53753. {name: 'highest', defaultTooltip: true}
  53754. ],
  53755. /**
  53756. * @type {Array.<string>}
  53757. * @readOnly
  53758. */
  53759. dimensions: null,
  53760. /**
  53761. * @override
  53762. */
  53763. defaultOption: {
  53764. zlevel: 0,
  53765. z: 2,
  53766. coordinateSystem: 'cartesian2d',
  53767. legendHoverLink: true,
  53768. hoverAnimation: true,
  53769. // xAxisIndex: 0,
  53770. // yAxisIndex: 0,
  53771. layout: null, // 'horizontal' or 'vertical'
  53772. itemStyle: {
  53773. color: '#c23531', // 阳线 positive
  53774. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  53775. borderWidth: 1,
  53776. // FIXME
  53777. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  53778. borderColor: '#c23531',
  53779. borderColor0: '#314656'
  53780. },
  53781. emphasis: {
  53782. itemStyle: {
  53783. borderWidth: 2
  53784. }
  53785. },
  53786. barMaxWidth: null,
  53787. barMinWidth: null,
  53788. barWidth: null,
  53789. large: true,
  53790. largeThreshold: 600,
  53791. progressive: 3e3,
  53792. progressiveThreshold: 1e4,
  53793. progressiveChunkMode: 'mod',
  53794. animationUpdate: false,
  53795. animationEasing: 'linear',
  53796. animationDuration: 300
  53797. },
  53798. /**
  53799. * Get dimension for shadow in dataZoom
  53800. * @return {string} dimension name
  53801. */
  53802. getShadowDim: function () {
  53803. return 'open';
  53804. },
  53805. brushSelector: function (dataIndex, data, selectors) {
  53806. var itemLayout = data.getItemLayout(dataIndex);
  53807. return itemLayout && selectors.rect(itemLayout.brushRect);
  53808. }
  53809. });
  53810. mixin(CandlestickSeries, seriesModelMixin, true);
  53811. /*
  53812. * Licensed to the Apache Software Foundation (ASF) under one
  53813. * or more contributor license agreements. See the NOTICE file
  53814. * distributed with this work for additional information
  53815. * regarding copyright ownership. The ASF licenses this file
  53816. * to you under the Apache License, Version 2.0 (the
  53817. * "License"); you may not use this file except in compliance
  53818. * with the License. You may obtain a copy of the License at
  53819. *
  53820. * http://www.apache.org/licenses/LICENSE-2.0
  53821. *
  53822. * Unless required by applicable law or agreed to in writing,
  53823. * software distributed under the License is distributed on an
  53824. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53825. * KIND, either express or implied. See the License for the
  53826. * specific language governing permissions and limitations
  53827. * under the License.
  53828. */
  53829. var NORMAL_ITEM_STYLE_PATH$1 = ['itemStyle'];
  53830. var EMPHASIS_ITEM_STYLE_PATH$1 = ['emphasis', 'itemStyle'];
  53831. var SKIP_PROPS = ['color', 'color0', 'borderColor', 'borderColor0'];
  53832. var CandlestickView = Chart.extend({
  53833. type: 'candlestick',
  53834. render: function (seriesModel, ecModel, api) {
  53835. this._updateDrawMode(seriesModel);
  53836. this._isLargeDraw
  53837. ? this._renderLarge(seriesModel)
  53838. : this._renderNormal(seriesModel);
  53839. },
  53840. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  53841. this._clear();
  53842. this._updateDrawMode(seriesModel);
  53843. },
  53844. incrementalRender: function (params, seriesModel, ecModel, api) {
  53845. this._isLargeDraw
  53846. ? this._incrementalRenderLarge(params, seriesModel)
  53847. : this._incrementalRenderNormal(params, seriesModel);
  53848. },
  53849. _updateDrawMode: function (seriesModel) {
  53850. var isLargeDraw = seriesModel.pipelineContext.large;
  53851. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  53852. this._isLargeDraw = isLargeDraw;
  53853. this._clear();
  53854. }
  53855. },
  53856. _renderNormal: function (seriesModel) {
  53857. var data = seriesModel.getData();
  53858. var oldData = this._data;
  53859. var group = this.group;
  53860. var isSimpleBox = data.getLayout('isSimpleBox');
  53861. // There is no old data only when first rendering or switching from
  53862. // stream mode to normal mode, where previous elements should be removed.
  53863. if (!this._data) {
  53864. group.removeAll();
  53865. }
  53866. data.diff(oldData)
  53867. .add(function (newIdx) {
  53868. if (data.hasValue(newIdx)) {
  53869. var el;
  53870. var itemLayout = data.getItemLayout(newIdx);
  53871. el = createNormalBox$1(itemLayout, newIdx, true);
  53872. initProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  53873. setBoxCommon(el, data, newIdx, isSimpleBox);
  53874. group.add(el);
  53875. data.setItemGraphicEl(newIdx, el);
  53876. }
  53877. })
  53878. .update(function (newIdx, oldIdx) {
  53879. var el = oldData.getItemGraphicEl(oldIdx);
  53880. // Empty data
  53881. if (!data.hasValue(newIdx)) {
  53882. group.remove(el);
  53883. return;
  53884. }
  53885. var itemLayout = data.getItemLayout(newIdx);
  53886. if (!el) {
  53887. el = createNormalBox$1(itemLayout, newIdx);
  53888. }
  53889. else {
  53890. updateProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  53891. }
  53892. setBoxCommon(el, data, newIdx, isSimpleBox);
  53893. group.add(el);
  53894. data.setItemGraphicEl(newIdx, el);
  53895. })
  53896. .remove(function (oldIdx) {
  53897. var el = oldData.getItemGraphicEl(oldIdx);
  53898. el && group.remove(el);
  53899. })
  53900. .execute();
  53901. this._data = data;
  53902. },
  53903. _renderLarge: function (seriesModel) {
  53904. this._clear();
  53905. createLarge$1(seriesModel, this.group);
  53906. },
  53907. _incrementalRenderNormal: function (params, seriesModel) {
  53908. var data = seriesModel.getData();
  53909. var isSimpleBox = data.getLayout('isSimpleBox');
  53910. var dataIndex;
  53911. while ((dataIndex = params.next()) != null) {
  53912. var el;
  53913. var itemLayout = data.getItemLayout(dataIndex);
  53914. el = createNormalBox$1(itemLayout, dataIndex);
  53915. setBoxCommon(el, data, dataIndex, isSimpleBox);
  53916. el.incremental = true;
  53917. this.group.add(el);
  53918. }
  53919. },
  53920. _incrementalRenderLarge: function (params, seriesModel) {
  53921. createLarge$1(seriesModel, this.group, true);
  53922. },
  53923. remove: function (ecModel) {
  53924. this._clear();
  53925. },
  53926. _clear: function () {
  53927. this.group.removeAll();
  53928. this._data = null;
  53929. },
  53930. dispose: noop
  53931. });
  53932. var NormalBoxPath = Path.extend({
  53933. type: 'normalCandlestickBox',
  53934. shape: {},
  53935. buildPath: function (ctx, shape) {
  53936. var ends = shape.points;
  53937. if (this.__simpleBox) {
  53938. ctx.moveTo(ends[4][0], ends[4][1]);
  53939. ctx.lineTo(ends[6][0], ends[6][1]);
  53940. }
  53941. else {
  53942. ctx.moveTo(ends[0][0], ends[0][1]);
  53943. ctx.lineTo(ends[1][0], ends[1][1]);
  53944. ctx.lineTo(ends[2][0], ends[2][1]);
  53945. ctx.lineTo(ends[3][0], ends[3][1]);
  53946. ctx.closePath();
  53947. ctx.moveTo(ends[4][0], ends[4][1]);
  53948. ctx.lineTo(ends[5][0], ends[5][1]);
  53949. ctx.moveTo(ends[6][0], ends[6][1]);
  53950. ctx.lineTo(ends[7][0], ends[7][1]);
  53951. }
  53952. }
  53953. });
  53954. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  53955. var ends = itemLayout.ends;
  53956. return new NormalBoxPath({
  53957. shape: {
  53958. points: isInit
  53959. ? transInit$1(ends, itemLayout)
  53960. : ends
  53961. },
  53962. z2: 100
  53963. });
  53964. }
  53965. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  53966. var itemModel = data.getItemModel(dataIndex);
  53967. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH$1);
  53968. var color = data.getItemVisual(dataIndex, 'color');
  53969. var borderColor = data.getItemVisual(dataIndex, 'borderColor') || color;
  53970. // Color must be excluded.
  53971. // Because symbol provide setColor individually to set fill and stroke
  53972. var itemStyle = normalItemStyleModel.getItemStyle(SKIP_PROPS);
  53973. el.useStyle(itemStyle);
  53974. el.style.strokeNoScale = true;
  53975. el.style.fill = color;
  53976. el.style.stroke = borderColor;
  53977. el.__simpleBox = isSimpleBox;
  53978. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH$1).getItemStyle();
  53979. setHoverStyle(el, hoverStyle);
  53980. }
  53981. function transInit$1(points, itemLayout) {
  53982. return map(points, function (point) {
  53983. point = point.slice();
  53984. point[1] = itemLayout.initBaseline;
  53985. return point;
  53986. });
  53987. }
  53988. var LargeBoxPath = Path.extend({
  53989. type: 'largeCandlestickBox',
  53990. shape: {},
  53991. buildPath: function (ctx, shape) {
  53992. // Drawing lines is more efficient than drawing
  53993. // a whole line or drawing rects.
  53994. var points = shape.points;
  53995. for (var i = 0; i < points.length;) {
  53996. if (this.__sign === points[i++]) {
  53997. var x = points[i++];
  53998. ctx.moveTo(x, points[i++]);
  53999. ctx.lineTo(x, points[i++]);
  54000. }
  54001. else {
  54002. i += 3;
  54003. }
  54004. }
  54005. }
  54006. });
  54007. function createLarge$1(seriesModel, group, incremental) {
  54008. var data = seriesModel.getData();
  54009. var largePoints = data.getLayout('largePoints');
  54010. var elP = new LargeBoxPath({
  54011. shape: {points: largePoints},
  54012. __sign: 1
  54013. });
  54014. group.add(elP);
  54015. var elN = new LargeBoxPath({
  54016. shape: {points: largePoints},
  54017. __sign: -1
  54018. });
  54019. group.add(elN);
  54020. setLargeStyle$1(1, elP, seriesModel, data);
  54021. setLargeStyle$1(-1, elN, seriesModel, data);
  54022. if (incremental) {
  54023. elP.incremental = true;
  54024. elN.incremental = true;
  54025. }
  54026. }
  54027. function setLargeStyle$1(sign, el, seriesModel, data) {
  54028. var suffix = sign > 0 ? 'P' : 'N';
  54029. var borderColor = data.getVisual('borderColor' + suffix)
  54030. || data.getVisual('color' + suffix);
  54031. // Color must be excluded.
  54032. // Because symbol provide setColor individually to set fill and stroke
  54033. var itemStyle = seriesModel.getModel(NORMAL_ITEM_STYLE_PATH$1).getItemStyle(SKIP_PROPS);
  54034. el.useStyle(itemStyle);
  54035. el.style.fill = null;
  54036. el.style.stroke = borderColor;
  54037. // No different
  54038. // el.style.lineWidth = .5;
  54039. }
  54040. /*
  54041. * Licensed to the Apache Software Foundation (ASF) under one
  54042. * or more contributor license agreements. See the NOTICE file
  54043. * distributed with this work for additional information
  54044. * regarding copyright ownership. The ASF licenses this file
  54045. * to you under the Apache License, Version 2.0 (the
  54046. * "License"); you may not use this file except in compliance
  54047. * with the License. You may obtain a copy of the License at
  54048. *
  54049. * http://www.apache.org/licenses/LICENSE-2.0
  54050. *
  54051. * Unless required by applicable law or agreed to in writing,
  54052. * software distributed under the License is distributed on an
  54053. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54054. * KIND, either express or implied. See the License for the
  54055. * specific language governing permissions and limitations
  54056. * under the License.
  54057. */
  54058. var preprocessor = function (option) {
  54059. if (!option || !isArray(option.series)) {
  54060. return;
  54061. }
  54062. // Translate 'k' to 'candlestick'.
  54063. each$1(option.series, function (seriesItem) {
  54064. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  54065. seriesItem.type = 'candlestick';
  54066. }
  54067. });
  54068. };
  54069. /*
  54070. * Licensed to the Apache Software Foundation (ASF) under one
  54071. * or more contributor license agreements. See the NOTICE file
  54072. * distributed with this work for additional information
  54073. * regarding copyright ownership. The ASF licenses this file
  54074. * to you under the Apache License, Version 2.0 (the
  54075. * "License"); you may not use this file except in compliance
  54076. * with the License. You may obtain a copy of the License at
  54077. *
  54078. * http://www.apache.org/licenses/LICENSE-2.0
  54079. *
  54080. * Unless required by applicable law or agreed to in writing,
  54081. * software distributed under the License is distributed on an
  54082. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54083. * KIND, either express or implied. See the License for the
  54084. * specific language governing permissions and limitations
  54085. * under the License.
  54086. */
  54087. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  54088. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  54089. var positiveColorQuery = ['itemStyle', 'color'];
  54090. var negativeColorQuery = ['itemStyle', 'color0'];
  54091. var candlestickVisual = {
  54092. seriesType: 'candlestick',
  54093. plan: createRenderPlanner(),
  54094. // For legend.
  54095. performRawSeries: true,
  54096. reset: function (seriesModel, ecModel) {
  54097. var data = seriesModel.getData();
  54098. var isLargeRender = seriesModel.pipelineContext.large;
  54099. data.setVisual({
  54100. legendSymbol: 'roundRect',
  54101. colorP: getColor(1, seriesModel),
  54102. colorN: getColor(-1, seriesModel),
  54103. borderColorP: getBorderColor(1, seriesModel),
  54104. borderColorN: getBorderColor(-1, seriesModel)
  54105. });
  54106. // Only visible series has each data be visual encoded
  54107. if (ecModel.isSeriesFiltered(seriesModel)) {
  54108. return;
  54109. }
  54110. return !isLargeRender && {progress: progress};
  54111. function progress(params, data) {
  54112. var dataIndex;
  54113. while ((dataIndex = params.next()) != null) {
  54114. var itemModel = data.getItemModel(dataIndex);
  54115. var sign = data.getItemLayout(dataIndex).sign;
  54116. data.setItemVisual(
  54117. dataIndex,
  54118. {
  54119. color: getColor(sign, itemModel),
  54120. borderColor: getBorderColor(sign, itemModel)
  54121. }
  54122. );
  54123. }
  54124. }
  54125. function getColor(sign, model) {
  54126. return model.get(
  54127. sign > 0 ? positiveColorQuery : negativeColorQuery
  54128. );
  54129. }
  54130. function getBorderColor(sign, model) {
  54131. return model.get(
  54132. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  54133. );
  54134. }
  54135. }
  54136. };
  54137. /*
  54138. * Licensed to the Apache Software Foundation (ASF) under one
  54139. * or more contributor license agreements. See the NOTICE file
  54140. * distributed with this work for additional information
  54141. * regarding copyright ownership. The ASF licenses this file
  54142. * to you under the Apache License, Version 2.0 (the
  54143. * "License"); you may not use this file except in compliance
  54144. * with the License. You may obtain a copy of the License at
  54145. *
  54146. * http://www.apache.org/licenses/LICENSE-2.0
  54147. *
  54148. * Unless required by applicable law or agreed to in writing,
  54149. * software distributed under the License is distributed on an
  54150. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54151. * KIND, either express or implied. See the License for the
  54152. * specific language governing permissions and limitations
  54153. * under the License.
  54154. */
  54155. /* global Float32Array */
  54156. var LargeArr$1 = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  54157. var candlestickLayout = {
  54158. seriesType: 'candlestick',
  54159. plan: createRenderPlanner(),
  54160. reset: function (seriesModel) {
  54161. var coordSys = seriesModel.coordinateSystem;
  54162. var data = seriesModel.getData();
  54163. var candleWidth = calculateCandleWidth(seriesModel, data);
  54164. var cDimIdx = 0;
  54165. var vDimIdx = 1;
  54166. var coordDims = ['x', 'y'];
  54167. var cDim = data.mapDimension(coordDims[cDimIdx]);
  54168. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  54169. var openDim = vDims[0];
  54170. var closeDim = vDims[1];
  54171. var lowestDim = vDims[2];
  54172. var highestDim = vDims[3];
  54173. data.setLayout({
  54174. candleWidth: candleWidth,
  54175. // The value is experimented visually.
  54176. isSimpleBox: candleWidth <= 1.3
  54177. });
  54178. if (cDim == null || vDims.length < 4) {
  54179. return;
  54180. }
  54181. return {
  54182. progress: seriesModel.pipelineContext.large
  54183. ? largeProgress : normalProgress
  54184. };
  54185. function normalProgress(params, data) {
  54186. var dataIndex;
  54187. while ((dataIndex = params.next()) != null) {
  54188. var axisDimVal = data.get(cDim, dataIndex);
  54189. var openVal = data.get(openDim, dataIndex);
  54190. var closeVal = data.get(closeDim, dataIndex);
  54191. var lowestVal = data.get(lowestDim, dataIndex);
  54192. var highestVal = data.get(highestDim, dataIndex);
  54193. var ocLow = Math.min(openVal, closeVal);
  54194. var ocHigh = Math.max(openVal, closeVal);
  54195. var ocLowPoint = getPoint(ocLow, axisDimVal);
  54196. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  54197. var lowestPoint = getPoint(lowestVal, axisDimVal);
  54198. var highestPoint = getPoint(highestVal, axisDimVal);
  54199. var ends = [];
  54200. addBodyEnd(ends, ocHighPoint, 0);
  54201. addBodyEnd(ends, ocLowPoint, 1);
  54202. ends.push(
  54203. subPixelOptimizePoint(highestPoint),
  54204. subPixelOptimizePoint(ocHighPoint),
  54205. subPixelOptimizePoint(lowestPoint),
  54206. subPixelOptimizePoint(ocLowPoint)
  54207. );
  54208. data.setItemLayout(dataIndex, {
  54209. sign: getSign(data, dataIndex, openVal, closeVal, closeDim),
  54210. initBaseline: openVal > closeVal
  54211. ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx], // open point.
  54212. ends: ends,
  54213. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  54214. });
  54215. }
  54216. function getPoint(val, axisDimVal) {
  54217. var p = [];
  54218. p[cDimIdx] = axisDimVal;
  54219. p[vDimIdx] = val;
  54220. return (isNaN(axisDimVal) || isNaN(val))
  54221. ? [NaN, NaN]
  54222. : coordSys.dataToPoint(p);
  54223. }
  54224. function addBodyEnd(ends, point, start) {
  54225. var point1 = point.slice();
  54226. var point2 = point.slice();
  54227. point1[cDimIdx] = subPixelOptimize(
  54228. point1[cDimIdx] + candleWidth / 2, 1, false
  54229. );
  54230. point2[cDimIdx] = subPixelOptimize(
  54231. point2[cDimIdx] - candleWidth / 2, 1, true
  54232. );
  54233. start
  54234. ? ends.push(point1, point2)
  54235. : ends.push(point2, point1);
  54236. }
  54237. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  54238. var pmin = getPoint(lowestVal, axisDimVal);
  54239. var pmax = getPoint(highestVal, axisDimVal);
  54240. pmin[cDimIdx] -= candleWidth / 2;
  54241. pmax[cDimIdx] -= candleWidth / 2;
  54242. return {
  54243. x: pmin[0],
  54244. y: pmin[1],
  54245. width: vDimIdx ? candleWidth : pmax[0] - pmin[0],
  54246. height: vDimIdx ? pmax[1] - pmin[1] : candleWidth
  54247. };
  54248. }
  54249. function subPixelOptimizePoint(point) {
  54250. point[cDimIdx] = subPixelOptimize(point[cDimIdx], 1);
  54251. return point;
  54252. }
  54253. }
  54254. function largeProgress(params, data) {
  54255. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  54256. var points = new LargeArr$1(params.count * 5);
  54257. var offset = 0;
  54258. var point;
  54259. var tmpIn = [];
  54260. var tmpOut = [];
  54261. var dataIndex;
  54262. while ((dataIndex = params.next()) != null) {
  54263. var axisDimVal = data.get(cDim, dataIndex);
  54264. var openVal = data.get(openDim, dataIndex);
  54265. var closeVal = data.get(closeDim, dataIndex);
  54266. var lowestVal = data.get(lowestDim, dataIndex);
  54267. var highestVal = data.get(highestDim, dataIndex);
  54268. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  54269. points[offset++] = NaN;
  54270. offset += 4;
  54271. continue;
  54272. }
  54273. points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim);
  54274. tmpIn[cDimIdx] = axisDimVal;
  54275. tmpIn[vDimIdx] = lowestVal;
  54276. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  54277. points[offset++] = point ? point[0] : NaN;
  54278. points[offset++] = point ? point[1] : NaN;
  54279. tmpIn[vDimIdx] = highestVal;
  54280. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  54281. points[offset++] = point ? point[1] : NaN;
  54282. }
  54283. data.setLayout('largePoints', points);
  54284. }
  54285. }
  54286. };
  54287. function getSign(data, dataIndex, openVal, closeVal, closeDim) {
  54288. var sign;
  54289. if (openVal > closeVal) {
  54290. sign = -1;
  54291. }
  54292. else if (openVal < closeVal) {
  54293. sign = 1;
  54294. }
  54295. else {
  54296. sign = dataIndex > 0
  54297. // If close === open, compare with close of last record
  54298. ? (data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1)
  54299. // No record of previous, set to be positive
  54300. : 1;
  54301. }
  54302. return sign;
  54303. }
  54304. function calculateCandleWidth(seriesModel, data) {
  54305. var baseAxis = seriesModel.getBaseAxis();
  54306. var extent;
  54307. var bandWidth = baseAxis.type === 'category'
  54308. ? baseAxis.getBandWidth()
  54309. : (
  54310. extent = baseAxis.getExtent(),
  54311. Math.abs(extent[1] - extent[0]) / data.count()
  54312. );
  54313. var barMaxWidth = parsePercent$1(
  54314. retrieve2(seriesModel.get('barMaxWidth'), bandWidth),
  54315. bandWidth
  54316. );
  54317. var barMinWidth = parsePercent$1(
  54318. retrieve2(seriesModel.get('barMinWidth'), 1),
  54319. bandWidth
  54320. );
  54321. var barWidth = seriesModel.get('barWidth');
  54322. return barWidth != null
  54323. ? parsePercent$1(barWidth, bandWidth)
  54324. // Put max outer to ensure bar visible in spite of overlap.
  54325. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  54326. }
  54327. /*
  54328. * Licensed to the Apache Software Foundation (ASF) under one
  54329. * or more contributor license agreements. See the NOTICE file
  54330. * distributed with this work for additional information
  54331. * regarding copyright ownership. The ASF licenses this file
  54332. * to you under the Apache License, Version 2.0 (the
  54333. * "License"); you may not use this file except in compliance
  54334. * with the License. You may obtain a copy of the License at
  54335. *
  54336. * http://www.apache.org/licenses/LICENSE-2.0
  54337. *
  54338. * Unless required by applicable law or agreed to in writing,
  54339. * software distributed under the License is distributed on an
  54340. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54341. * KIND, either express or implied. See the License for the
  54342. * specific language governing permissions and limitations
  54343. * under the License.
  54344. */
  54345. registerPreprocessor(preprocessor);
  54346. registerVisual(candlestickVisual);
  54347. registerLayout(candlestickLayout);
  54348. /*
  54349. * Licensed to the Apache Software Foundation (ASF) under one
  54350. * or more contributor license agreements. See the NOTICE file
  54351. * distributed with this work for additional information
  54352. * regarding copyright ownership. The ASF licenses this file
  54353. * to you under the Apache License, Version 2.0 (the
  54354. * "License"); you may not use this file except in compliance
  54355. * with the License. You may obtain a copy of the License at
  54356. *
  54357. * http://www.apache.org/licenses/LICENSE-2.0
  54358. *
  54359. * Unless required by applicable law or agreed to in writing,
  54360. * software distributed under the License is distributed on an
  54361. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54362. * KIND, either express or implied. See the License for the
  54363. * specific language governing permissions and limitations
  54364. * under the License.
  54365. */
  54366. SeriesModel.extend({
  54367. type: 'series.effectScatter',
  54368. dependencies: ['grid', 'polar'],
  54369. getInitialData: function (option, ecModel) {
  54370. return createListFromArray(this.getSource(), this);
  54371. },
  54372. brushSelector: 'point',
  54373. defaultOption: {
  54374. coordinateSystem: 'cartesian2d',
  54375. zlevel: 0,
  54376. z: 2,
  54377. legendHoverLink: true,
  54378. effectType: 'ripple',
  54379. progressive: 0,
  54380. // When to show the effect, option: 'render'|'emphasis'
  54381. showEffectOn: 'render',
  54382. // Ripple effect config
  54383. rippleEffect: {
  54384. period: 4,
  54385. // Scale of ripple
  54386. scale: 2.5,
  54387. // Brush type can be fill or stroke
  54388. brushType: 'fill'
  54389. },
  54390. // Cartesian coordinate system
  54391. // xAxisIndex: 0,
  54392. // yAxisIndex: 0,
  54393. // Polar coordinate system
  54394. // polarIndex: 0,
  54395. // Geo coordinate system
  54396. // geoIndex: 0,
  54397. // symbol: null, // 图形类型
  54398. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  54399. // symbolRotate: null, // 图形旋转控制
  54400. // large: false,
  54401. // Available when large is true
  54402. // largeThreshold: 2000,
  54403. // itemStyle: {
  54404. // opacity: 1
  54405. // }
  54406. }
  54407. });
  54408. /*
  54409. * Licensed to the Apache Software Foundation (ASF) under one
  54410. * or more contributor license agreements. See the NOTICE file
  54411. * distributed with this work for additional information
  54412. * regarding copyright ownership. The ASF licenses this file
  54413. * to you under the Apache License, Version 2.0 (the
  54414. * "License"); you may not use this file except in compliance
  54415. * with the License. You may obtain a copy of the License at
  54416. *
  54417. * http://www.apache.org/licenses/LICENSE-2.0
  54418. *
  54419. * Unless required by applicable law or agreed to in writing,
  54420. * software distributed under the License is distributed on an
  54421. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54422. * KIND, either express or implied. See the License for the
  54423. * specific language governing permissions and limitations
  54424. * under the License.
  54425. */
  54426. /**
  54427. * Symbol with ripple effect
  54428. * @module echarts/chart/helper/EffectSymbol
  54429. */
  54430. var EFFECT_RIPPLE_NUMBER = 3;
  54431. function normalizeSymbolSize$1(symbolSize) {
  54432. if (!isArray(symbolSize)) {
  54433. symbolSize = [+symbolSize, +symbolSize];
  54434. }
  54435. return symbolSize;
  54436. }
  54437. function updateRipplePath(rippleGroup, effectCfg) {
  54438. rippleGroup.eachChild(function (ripplePath) {
  54439. ripplePath.attr({
  54440. z: effectCfg.z,
  54441. zlevel: effectCfg.zlevel,
  54442. style: {
  54443. stroke: effectCfg.brushType === 'stroke' ? effectCfg.color : null,
  54444. fill: effectCfg.brushType === 'fill' ? effectCfg.color : null
  54445. }
  54446. });
  54447. });
  54448. }
  54449. /**
  54450. * @constructor
  54451. * @param {module:echarts/data/List} data
  54452. * @param {number} idx
  54453. * @extends {module:zrender/graphic/Group}
  54454. */
  54455. function EffectSymbol(data, idx) {
  54456. Group.call(this);
  54457. var symbol = new SymbolClz$1(data, idx);
  54458. var rippleGroup = new Group();
  54459. this.add(symbol);
  54460. this.add(rippleGroup);
  54461. rippleGroup.beforeUpdate = function () {
  54462. this.attr(symbol.getScale());
  54463. };
  54464. this.updateData(data, idx);
  54465. }
  54466. var effectSymbolProto = EffectSymbol.prototype;
  54467. effectSymbolProto.stopEffectAnimation = function () {
  54468. this.childAt(1).removeAll();
  54469. };
  54470. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  54471. var symbolType = effectCfg.symbolType;
  54472. var color = effectCfg.color;
  54473. var rippleGroup = this.childAt(1);
  54474. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  54475. // var ripplePath = createSymbol(
  54476. // symbolType, -0.5, -0.5, 1, 1, color
  54477. // );
  54478. // If width/height are set too small (e.g., set to 1) on ios10
  54479. // and macOS Sierra, a circle stroke become a rect, no matter what
  54480. // the scale is set. So we set width/height as 2. See #4136.
  54481. var ripplePath = createSymbol(
  54482. symbolType, -1, -1, 2, 2, color
  54483. );
  54484. ripplePath.attr({
  54485. style: {
  54486. strokeNoScale: true
  54487. },
  54488. z2: 99,
  54489. silent: true,
  54490. scale: [0.5, 0.5]
  54491. });
  54492. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  54493. // TODO Configurable effectCfg.period
  54494. ripplePath.animate('', true)
  54495. .when(effectCfg.period, {
  54496. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  54497. })
  54498. .delay(delay)
  54499. .start();
  54500. ripplePath.animateStyle(true)
  54501. .when(effectCfg.period, {
  54502. opacity: 0
  54503. })
  54504. .delay(delay)
  54505. .start();
  54506. rippleGroup.add(ripplePath);
  54507. }
  54508. updateRipplePath(rippleGroup, effectCfg);
  54509. };
  54510. /**
  54511. * Update effect symbol
  54512. */
  54513. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  54514. var oldEffectCfg = this._effectCfg;
  54515. var rippleGroup = this.childAt(1);
  54516. // Must reinitialize effect if following configuration changed
  54517. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  54518. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  54519. var propName = DIFFICULT_PROPS[i];
  54520. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  54521. this.stopEffectAnimation();
  54522. this.startEffectAnimation(effectCfg);
  54523. return;
  54524. }
  54525. }
  54526. updateRipplePath(rippleGroup, effectCfg);
  54527. };
  54528. /**
  54529. * Highlight symbol
  54530. */
  54531. effectSymbolProto.highlight = function () {
  54532. this.trigger('emphasis');
  54533. };
  54534. /**
  54535. * Downplay symbol
  54536. */
  54537. effectSymbolProto.downplay = function () {
  54538. this.trigger('normal');
  54539. };
  54540. /**
  54541. * Update symbol properties
  54542. * @param {module:echarts/data/List} data
  54543. * @param {number} idx
  54544. */
  54545. effectSymbolProto.updateData = function (data, idx) {
  54546. var seriesModel = data.hostModel;
  54547. this.childAt(0).updateData(data, idx);
  54548. var rippleGroup = this.childAt(1);
  54549. var itemModel = data.getItemModel(idx);
  54550. var symbolType = data.getItemVisual(idx, 'symbol');
  54551. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  54552. var color = data.getItemVisual(idx, 'color');
  54553. rippleGroup.attr('scale', symbolSize);
  54554. rippleGroup.traverse(function (ripplePath) {
  54555. ripplePath.attr({
  54556. fill: color
  54557. });
  54558. });
  54559. var symbolOffset = itemModel.getShallow('symbolOffset');
  54560. if (symbolOffset) {
  54561. var pos = rippleGroup.position;
  54562. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  54563. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  54564. }
  54565. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  54566. var effectCfg = {};
  54567. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  54568. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  54569. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  54570. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  54571. effectCfg.effectOffset = idx / data.count();
  54572. effectCfg.z = itemModel.getShallow('z') || 0;
  54573. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  54574. effectCfg.symbolType = symbolType;
  54575. effectCfg.color = color;
  54576. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  54577. if (effectCfg.showEffectOn === 'render') {
  54578. this._effectCfg
  54579. ? this.updateEffectAnimation(effectCfg)
  54580. : this.startEffectAnimation(effectCfg);
  54581. this._effectCfg = effectCfg;
  54582. }
  54583. else {
  54584. // Not keep old effect config
  54585. this._effectCfg = null;
  54586. this.stopEffectAnimation();
  54587. var symbol = this.childAt(0);
  54588. var onEmphasis = function () {
  54589. symbol.highlight();
  54590. if (effectCfg.showEffectOn !== 'render') {
  54591. this.startEffectAnimation(effectCfg);
  54592. }
  54593. };
  54594. var onNormal = function () {
  54595. symbol.downplay();
  54596. if (effectCfg.showEffectOn !== 'render') {
  54597. this.stopEffectAnimation();
  54598. }
  54599. };
  54600. this.on('mouseover', onEmphasis, this)
  54601. .on('mouseout', onNormal, this)
  54602. .on('emphasis', onEmphasis, this)
  54603. .on('normal', onNormal, this);
  54604. }
  54605. this._effectCfg = effectCfg;
  54606. };
  54607. effectSymbolProto.fadeOut = function (cb) {
  54608. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  54609. cb && cb();
  54610. };
  54611. inherits(EffectSymbol, Group);
  54612. /*
  54613. * Licensed to the Apache Software Foundation (ASF) under one
  54614. * or more contributor license agreements. See the NOTICE file
  54615. * distributed with this work for additional information
  54616. * regarding copyright ownership. The ASF licenses this file
  54617. * to you under the Apache License, Version 2.0 (the
  54618. * "License"); you may not use this file except in compliance
  54619. * with the License. You may obtain a copy of the License at
  54620. *
  54621. * http://www.apache.org/licenses/LICENSE-2.0
  54622. *
  54623. * Unless required by applicable law or agreed to in writing,
  54624. * software distributed under the License is distributed on an
  54625. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54626. * KIND, either express or implied. See the License for the
  54627. * specific language governing permissions and limitations
  54628. * under the License.
  54629. */
  54630. extendChartView({
  54631. type: 'effectScatter',
  54632. init: function () {
  54633. this._symbolDraw = new SymbolDraw(EffectSymbol);
  54634. },
  54635. render: function (seriesModel, ecModel, api) {
  54636. var data = seriesModel.getData();
  54637. var effectSymbolDraw = this._symbolDraw;
  54638. effectSymbolDraw.updateData(data);
  54639. this.group.add(effectSymbolDraw.group);
  54640. },
  54641. updateTransform: function (seriesModel, ecModel, api) {
  54642. var data = seriesModel.getData();
  54643. this.group.dirty();
  54644. var res = pointsLayout().reset(seriesModel);
  54645. if (res.progress) {
  54646. res.progress({ start: 0, end: data.count() }, data);
  54647. }
  54648. this._symbolDraw.updateLayout(data);
  54649. },
  54650. _updateGroupTransform: function (seriesModel) {
  54651. var coordSys = seriesModel.coordinateSystem;
  54652. if (coordSys && coordSys.getRoamTransform) {
  54653. this.group.transform = clone$2(coordSys.getRoamTransform());
  54654. this.group.decomposeTransform();
  54655. }
  54656. },
  54657. remove: function (ecModel, api) {
  54658. this._symbolDraw && this._symbolDraw.remove(api);
  54659. },
  54660. dispose: function () {}
  54661. });
  54662. /*
  54663. * Licensed to the Apache Software Foundation (ASF) under one
  54664. * or more contributor license agreements. See the NOTICE file
  54665. * distributed with this work for additional information
  54666. * regarding copyright ownership. The ASF licenses this file
  54667. * to you under the Apache License, Version 2.0 (the
  54668. * "License"); you may not use this file except in compliance
  54669. * with the License. You may obtain a copy of the License at
  54670. *
  54671. * http://www.apache.org/licenses/LICENSE-2.0
  54672. *
  54673. * Unless required by applicable law or agreed to in writing,
  54674. * software distributed under the License is distributed on an
  54675. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54676. * KIND, either express or implied. See the License for the
  54677. * specific language governing permissions and limitations
  54678. * under the License.
  54679. */
  54680. registerVisual(visualSymbol('effectScatter', 'circle'));
  54681. registerLayout(pointsLayout('effectScatter'));
  54682. /*
  54683. * Licensed to the Apache Software Foundation (ASF) under one
  54684. * or more contributor license agreements. See the NOTICE file
  54685. * distributed with this work for additional information
  54686. * regarding copyright ownership. The ASF licenses this file
  54687. * to you under the Apache License, Version 2.0 (the
  54688. * "License"); you may not use this file except in compliance
  54689. * with the License. You may obtain a copy of the License at
  54690. *
  54691. * http://www.apache.org/licenses/LICENSE-2.0
  54692. *
  54693. * Unless required by applicable law or agreed to in writing,
  54694. * software distributed under the License is distributed on an
  54695. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54696. * KIND, either express or implied. See the License for the
  54697. * specific language governing permissions and limitations
  54698. * under the License.
  54699. */
  54700. /* global Uint32Array, Float64Array, Float32Array */
  54701. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  54702. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  54703. function compatEc2(seriesOpt) {
  54704. var data = seriesOpt.data;
  54705. if (data && data[0] && data[0][0] && data[0][0].coord) {
  54706. if (__DEV__) {
  54707. console.warn('Lines data configuration has been changed to'
  54708. + ' { coords:[[1,2],[2,3]] }');
  54709. }
  54710. seriesOpt.data = map(data, function (itemOpt) {
  54711. var coords = [
  54712. itemOpt[0].coord, itemOpt[1].coord
  54713. ];
  54714. var target = {
  54715. coords: coords
  54716. };
  54717. if (itemOpt[0].name) {
  54718. target.fromName = itemOpt[0].name;
  54719. }
  54720. if (itemOpt[1].name) {
  54721. target.toName = itemOpt[1].name;
  54722. }
  54723. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  54724. });
  54725. }
  54726. }
  54727. var LinesSeries = SeriesModel.extend({
  54728. type: 'series.lines',
  54729. dependencies: ['grid', 'polar'],
  54730. visualColorAccessPath: 'lineStyle.color',
  54731. init: function (option) {
  54732. // The input data may be null/undefined.
  54733. option.data = option.data || [];
  54734. // Not using preprocessor because mergeOption may not have series.type
  54735. compatEc2(option);
  54736. var result = this._processFlatCoordsArray(option.data);
  54737. this._flatCoords = result.flatCoords;
  54738. this._flatCoordsOffset = result.flatCoordsOffset;
  54739. if (result.flatCoords) {
  54740. option.data = new Float32Array(result.count);
  54741. }
  54742. LinesSeries.superApply(this, 'init', arguments);
  54743. },
  54744. mergeOption: function (option) {
  54745. // The input data may be null/undefined.
  54746. option.data = option.data || [];
  54747. compatEc2(option);
  54748. if (option.data) {
  54749. // Only update when have option data to merge.
  54750. var result = this._processFlatCoordsArray(option.data);
  54751. this._flatCoords = result.flatCoords;
  54752. this._flatCoordsOffset = result.flatCoordsOffset;
  54753. if (result.flatCoords) {
  54754. option.data = new Float32Array(result.count);
  54755. }
  54756. }
  54757. LinesSeries.superApply(this, 'mergeOption', arguments);
  54758. },
  54759. appendData: function (params) {
  54760. var result = this._processFlatCoordsArray(params.data);
  54761. if (result.flatCoords) {
  54762. if (!this._flatCoords) {
  54763. this._flatCoords = result.flatCoords;
  54764. this._flatCoordsOffset = result.flatCoordsOffset;
  54765. }
  54766. else {
  54767. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  54768. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  54769. }
  54770. params.data = new Float32Array(result.count);
  54771. }
  54772. this.getRawData().appendData(params.data);
  54773. },
  54774. _getCoordsFromItemModel: function (idx) {
  54775. var itemModel = this.getData().getItemModel(idx);
  54776. var coords = (itemModel.option instanceof Array)
  54777. ? itemModel.option : itemModel.getShallow('coords');
  54778. if (__DEV__) {
  54779. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  54780. throw new Error(
  54781. 'Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.'
  54782. );
  54783. }
  54784. }
  54785. return coords;
  54786. },
  54787. getLineCoordsCount: function (idx) {
  54788. if (this._flatCoordsOffset) {
  54789. return this._flatCoordsOffset[idx * 2 + 1];
  54790. }
  54791. else {
  54792. return this._getCoordsFromItemModel(idx).length;
  54793. }
  54794. },
  54795. getLineCoords: function (idx, out) {
  54796. if (this._flatCoordsOffset) {
  54797. var offset = this._flatCoordsOffset[idx * 2];
  54798. var len = this._flatCoordsOffset[idx * 2 + 1];
  54799. for (var i = 0; i < len; i++) {
  54800. out[i] = out[i] || [];
  54801. out[i][0] = this._flatCoords[offset + i * 2];
  54802. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  54803. }
  54804. return len;
  54805. }
  54806. else {
  54807. var coords = this._getCoordsFromItemModel(idx);
  54808. for (var i = 0; i < coords.length; i++) {
  54809. out[i] = out[i] || [];
  54810. out[i][0] = coords[i][0];
  54811. out[i][1] = coords[i][1];
  54812. }
  54813. return coords.length;
  54814. }
  54815. },
  54816. _processFlatCoordsArray: function (data) {
  54817. var startOffset = 0;
  54818. if (this._flatCoords) {
  54819. startOffset = this._flatCoords.length;
  54820. }
  54821. // Stored as a typed array. In format
  54822. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  54823. if (typeof data[0] === 'number') {
  54824. var len = data.length;
  54825. // Store offset and len of each segment
  54826. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  54827. var coordsStorage = new Float64Arr(len);
  54828. var coordsCursor = 0;
  54829. var offsetCursor = 0;
  54830. var dataCount = 0;
  54831. for (var i = 0; i < len;) {
  54832. dataCount++;
  54833. var count = data[i++];
  54834. // Offset
  54835. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset;
  54836. // Len
  54837. coordsOffsetAndLenStorage[offsetCursor++] = count;
  54838. for (var k = 0; k < count; k++) {
  54839. var x = data[i++];
  54840. var y = data[i++];
  54841. coordsStorage[coordsCursor++] = x;
  54842. coordsStorage[coordsCursor++] = y;
  54843. if (i > len) {
  54844. if (__DEV__) {
  54845. throw new Error('Invalid data format.');
  54846. }
  54847. }
  54848. }
  54849. }
  54850. return {
  54851. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  54852. flatCoords: coordsStorage,
  54853. count: dataCount
  54854. };
  54855. }
  54856. return {
  54857. flatCoordsOffset: null,
  54858. flatCoords: null,
  54859. count: data.length
  54860. };
  54861. },
  54862. getInitialData: function (option, ecModel) {
  54863. if (__DEV__) {
  54864. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  54865. if (!CoordSys) {
  54866. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  54867. }
  54868. }
  54869. var lineData = new List(['value'], this);
  54870. lineData.hasItemOption = false;
  54871. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  54872. // dataItem is simply coords
  54873. if (dataItem instanceof Array) {
  54874. return NaN;
  54875. }
  54876. else {
  54877. lineData.hasItemOption = true;
  54878. var value = dataItem.value;
  54879. if (value != null) {
  54880. return value instanceof Array ? value[dimIndex] : value;
  54881. }
  54882. }
  54883. });
  54884. return lineData;
  54885. },
  54886. formatTooltip: function (dataIndex) {
  54887. var data = this.getData();
  54888. var itemModel = data.getItemModel(dataIndex);
  54889. var name = itemModel.get('name');
  54890. if (name) {
  54891. return name;
  54892. }
  54893. var fromName = itemModel.get('fromName');
  54894. var toName = itemModel.get('toName');
  54895. var html = [];
  54896. fromName != null && html.push(fromName);
  54897. toName != null && html.push(toName);
  54898. return encodeHTML(html.join(' > '));
  54899. },
  54900. preventIncremental: function () {
  54901. return !!this.get('effect.show');
  54902. },
  54903. getProgressive: function () {
  54904. var progressive = this.option.progressive;
  54905. if (progressive == null) {
  54906. return this.option.large ? 1e4 : this.get('progressive');
  54907. }
  54908. return progressive;
  54909. },
  54910. getProgressiveThreshold: function () {
  54911. var progressiveThreshold = this.option.progressiveThreshold;
  54912. if (progressiveThreshold == null) {
  54913. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  54914. }
  54915. return progressiveThreshold;
  54916. },
  54917. defaultOption: {
  54918. coordinateSystem: 'geo',
  54919. zlevel: 0,
  54920. z: 2,
  54921. legendHoverLink: true,
  54922. hoverAnimation: true,
  54923. // Cartesian coordinate system
  54924. xAxisIndex: 0,
  54925. yAxisIndex: 0,
  54926. symbol: ['none', 'none'],
  54927. symbolSize: [10, 10],
  54928. // Geo coordinate system
  54929. geoIndex: 0,
  54930. effect: {
  54931. show: false,
  54932. period: 4,
  54933. // Animation delay. support callback
  54934. // delay: 0,
  54935. // If move with constant speed px/sec
  54936. // period will be ignored if this property is > 0,
  54937. constantSpeed: 0,
  54938. symbol: 'circle',
  54939. symbolSize: 3,
  54940. loop: true,
  54941. // Length of trail, 0 - 1
  54942. trailLength: 0.2
  54943. // Same with lineStyle.color
  54944. // color
  54945. },
  54946. large: false,
  54947. // Available when large is true
  54948. largeThreshold: 2000,
  54949. // If lines are polyline
  54950. // polyline not support curveness, label, animation
  54951. polyline: false,
  54952. label: {
  54953. show: false,
  54954. position: 'end'
  54955. // distance: 5,
  54956. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  54957. },
  54958. lineStyle: {
  54959. opacity: 0.5
  54960. }
  54961. }
  54962. });
  54963. /*
  54964. * Licensed to the Apache Software Foundation (ASF) under one
  54965. * or more contributor license agreements. See the NOTICE file
  54966. * distributed with this work for additional information
  54967. * regarding copyright ownership. The ASF licenses this file
  54968. * to you under the Apache License, Version 2.0 (the
  54969. * "License"); you may not use this file except in compliance
  54970. * with the License. You may obtain a copy of the License at
  54971. *
  54972. * http://www.apache.org/licenses/LICENSE-2.0
  54973. *
  54974. * Unless required by applicable law or agreed to in writing,
  54975. * software distributed under the License is distributed on an
  54976. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54977. * KIND, either express or implied. See the License for the
  54978. * specific language governing permissions and limitations
  54979. * under the License.
  54980. */
  54981. /**
  54982. * Provide effect for line
  54983. * @module echarts/chart/helper/EffectLine
  54984. */
  54985. /**
  54986. * @constructor
  54987. * @extends {module:zrender/graphic/Group}
  54988. * @alias {module:echarts/chart/helper/Line}
  54989. */
  54990. function EffectLine(lineData, idx, seriesScope) {
  54991. Group.call(this);
  54992. this.add(this.createLine(lineData, idx, seriesScope));
  54993. this._updateEffectSymbol(lineData, idx);
  54994. }
  54995. var effectLineProto = EffectLine.prototype;
  54996. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  54997. return new Line$1(lineData, idx, seriesScope);
  54998. };
  54999. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  55000. var itemModel = lineData.getItemModel(idx);
  55001. var effectModel = itemModel.getModel('effect');
  55002. var size = effectModel.get('symbolSize');
  55003. var symbolType = effectModel.get('symbol');
  55004. if (!isArray(size)) {
  55005. size = [size, size];
  55006. }
  55007. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  55008. var symbol = this.childAt(1);
  55009. if (this._symbolType !== symbolType) {
  55010. // Remove previous
  55011. this.remove(symbol);
  55012. symbol = createSymbol(
  55013. symbolType, -0.5, -0.5, 1, 1, color
  55014. );
  55015. symbol.z2 = 100;
  55016. symbol.culling = true;
  55017. this.add(symbol);
  55018. }
  55019. // Symbol may be removed if loop is false
  55020. if (!symbol) {
  55021. return;
  55022. }
  55023. // Shadow color is same with color in default
  55024. symbol.setStyle('shadowColor', color);
  55025. symbol.setStyle(effectModel.getItemStyle(['color']));
  55026. symbol.attr('scale', size);
  55027. symbol.setColor(color);
  55028. symbol.attr('scale', size);
  55029. this._symbolType = symbolType;
  55030. this._updateEffectAnimation(lineData, effectModel, idx);
  55031. };
  55032. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  55033. var symbol = this.childAt(1);
  55034. if (!symbol) {
  55035. return;
  55036. }
  55037. var self = this;
  55038. var points = lineData.getItemLayout(idx);
  55039. var period = effectModel.get('period') * 1000;
  55040. var loop = effectModel.get('loop');
  55041. var constantSpeed = effectModel.get('constantSpeed');
  55042. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  55043. return idx / lineData.count() * period / 3;
  55044. });
  55045. var isDelayFunc = typeof delayExpr === 'function';
  55046. // Ignore when updating
  55047. symbol.ignore = true;
  55048. this.updateAnimationPoints(symbol, points);
  55049. if (constantSpeed > 0) {
  55050. period = this.getLineLength(symbol) / constantSpeed * 1000;
  55051. }
  55052. if (period !== this._period || loop !== this._loop) {
  55053. symbol.stopAnimation();
  55054. var delay = delayExpr;
  55055. if (isDelayFunc) {
  55056. delay = delayExpr(idx);
  55057. }
  55058. if (symbol.__t > 0) {
  55059. delay = -period * symbol.__t;
  55060. }
  55061. symbol.__t = 0;
  55062. var animator = symbol.animate('', loop)
  55063. .when(period, {
  55064. __t: 1
  55065. })
  55066. .delay(delay)
  55067. .during(function () {
  55068. self.updateSymbolPosition(symbol);
  55069. });
  55070. if (!loop) {
  55071. animator.done(function () {
  55072. self.remove(symbol);
  55073. });
  55074. }
  55075. animator.start();
  55076. }
  55077. this._period = period;
  55078. this._loop = loop;
  55079. };
  55080. effectLineProto.getLineLength = function (symbol) {
  55081. // Not so accurate
  55082. return (dist(symbol.__p1, symbol.__cp1)
  55083. + dist(symbol.__cp1, symbol.__p2));
  55084. };
  55085. effectLineProto.updateAnimationPoints = function (symbol, points) {
  55086. symbol.__p1 = points[0];
  55087. symbol.__p2 = points[1];
  55088. symbol.__cp1 = points[2] || [
  55089. (points[0][0] + points[1][0]) / 2,
  55090. (points[0][1] + points[1][1]) / 2
  55091. ];
  55092. };
  55093. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  55094. this.childAt(0).updateData(lineData, idx, seriesScope);
  55095. this._updateEffectSymbol(lineData, idx);
  55096. };
  55097. effectLineProto.updateSymbolPosition = function (symbol) {
  55098. var p1 = symbol.__p1;
  55099. var p2 = symbol.__p2;
  55100. var cp1 = symbol.__cp1;
  55101. var t = symbol.__t;
  55102. var pos = symbol.position;
  55103. var quadraticAt$$1 = quadraticAt;
  55104. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  55105. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  55106. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  55107. // Tangent
  55108. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  55109. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  55110. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  55111. symbol.ignore = false;
  55112. };
  55113. effectLineProto.updateLayout = function (lineData, idx) {
  55114. this.childAt(0).updateLayout(lineData, idx);
  55115. var effectModel = lineData.getItemModel(idx).getModel('effect');
  55116. this._updateEffectAnimation(lineData, effectModel, idx);
  55117. };
  55118. inherits(EffectLine, Group);
  55119. /*
  55120. * Licensed to the Apache Software Foundation (ASF) under one
  55121. * or more contributor license agreements. See the NOTICE file
  55122. * distributed with this work for additional information
  55123. * regarding copyright ownership. The ASF licenses this file
  55124. * to you under the Apache License, Version 2.0 (the
  55125. * "License"); you may not use this file except in compliance
  55126. * with the License. You may obtain a copy of the License at
  55127. *
  55128. * http://www.apache.org/licenses/LICENSE-2.0
  55129. *
  55130. * Unless required by applicable law or agreed to in writing,
  55131. * software distributed under the License is distributed on an
  55132. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55133. * KIND, either express or implied. See the License for the
  55134. * specific language governing permissions and limitations
  55135. * under the License.
  55136. */
  55137. /**
  55138. * @module echarts/chart/helper/Line
  55139. */
  55140. /**
  55141. * @constructor
  55142. * @extends {module:zrender/graphic/Group}
  55143. * @alias {module:echarts/chart/helper/Polyline}
  55144. */
  55145. function Polyline$2(lineData, idx, seriesScope) {
  55146. Group.call(this);
  55147. this._createPolyline(lineData, idx, seriesScope);
  55148. }
  55149. var polylineProto = Polyline$2.prototype;
  55150. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  55151. // var seriesModel = lineData.hostModel;
  55152. var points = lineData.getItemLayout(idx);
  55153. var line = new Polyline({
  55154. shape: {
  55155. points: points
  55156. }
  55157. });
  55158. this.add(line);
  55159. this._updateCommonStl(lineData, idx, seriesScope);
  55160. };
  55161. polylineProto.updateData = function (lineData, idx, seriesScope) {
  55162. var seriesModel = lineData.hostModel;
  55163. var line = this.childAt(0);
  55164. var target = {
  55165. shape: {
  55166. points: lineData.getItemLayout(idx)
  55167. }
  55168. };
  55169. updateProps(line, target, seriesModel, idx);
  55170. this._updateCommonStl(lineData, idx, seriesScope);
  55171. };
  55172. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  55173. var line = this.childAt(0);
  55174. var itemModel = lineData.getItemModel(idx);
  55175. var visualColor = lineData.getItemVisual(idx, 'color');
  55176. var lineStyle = seriesScope && seriesScope.lineStyle;
  55177. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  55178. if (!seriesScope || lineData.hasItemOption) {
  55179. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  55180. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  55181. }
  55182. line.useStyle(defaults(
  55183. {
  55184. strokeNoScale: true,
  55185. fill: 'none',
  55186. stroke: visualColor
  55187. },
  55188. lineStyle
  55189. ));
  55190. line.hoverStyle = hoverLineStyle;
  55191. setHoverStyle(this);
  55192. };
  55193. polylineProto.updateLayout = function (lineData, idx) {
  55194. var polyline = this.childAt(0);
  55195. polyline.setShape('points', lineData.getItemLayout(idx));
  55196. };
  55197. inherits(Polyline$2, Group);
  55198. /*
  55199. * Licensed to the Apache Software Foundation (ASF) under one
  55200. * or more contributor license agreements. See the NOTICE file
  55201. * distributed with this work for additional information
  55202. * regarding copyright ownership. The ASF licenses this file
  55203. * to you under the Apache License, Version 2.0 (the
  55204. * "License"); you may not use this file except in compliance
  55205. * with the License. You may obtain a copy of the License at
  55206. *
  55207. * http://www.apache.org/licenses/LICENSE-2.0
  55208. *
  55209. * Unless required by applicable law or agreed to in writing,
  55210. * software distributed under the License is distributed on an
  55211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55212. * KIND, either express or implied. See the License for the
  55213. * specific language governing permissions and limitations
  55214. * under the License.
  55215. */
  55216. /**
  55217. * Provide effect for line
  55218. * @module echarts/chart/helper/EffectLine
  55219. */
  55220. /**
  55221. * @constructor
  55222. * @extends {module:echarts/chart/helper/EffectLine}
  55223. * @alias {module:echarts/chart/helper/Polyline}
  55224. */
  55225. function EffectPolyline(lineData, idx, seriesScope) {
  55226. EffectLine.call(this, lineData, idx, seriesScope);
  55227. this._lastFrame = 0;
  55228. this._lastFramePercent = 0;
  55229. }
  55230. var effectPolylineProto = EffectPolyline.prototype;
  55231. // Overwrite
  55232. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  55233. return new Polyline$2(lineData, idx, seriesScope);
  55234. };
  55235. // Overwrite
  55236. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  55237. this._points = points;
  55238. var accLenArr = [0];
  55239. var len$$1 = 0;
  55240. for (var i = 1; i < points.length; i++) {
  55241. var p1 = points[i - 1];
  55242. var p2 = points[i];
  55243. len$$1 += dist(p1, p2);
  55244. accLenArr.push(len$$1);
  55245. }
  55246. if (len$$1 === 0) {
  55247. return;
  55248. }
  55249. for (var i = 0; i < accLenArr.length; i++) {
  55250. accLenArr[i] /= len$$1;
  55251. }
  55252. this._offsets = accLenArr;
  55253. this._length = len$$1;
  55254. };
  55255. // Overwrite
  55256. effectPolylineProto.getLineLength = function (symbol) {
  55257. return this._length;
  55258. };
  55259. // Overwrite
  55260. effectPolylineProto.updateSymbolPosition = function (symbol) {
  55261. var t = symbol.__t;
  55262. var points = this._points;
  55263. var offsets = this._offsets;
  55264. var len$$1 = points.length;
  55265. if (!offsets) {
  55266. // Has length 0
  55267. return;
  55268. }
  55269. var lastFrame = this._lastFrame;
  55270. var frame;
  55271. if (t < this._lastFramePercent) {
  55272. // Start from the next frame
  55273. // PENDING start from lastFrame ?
  55274. var start = Math.min(lastFrame + 1, len$$1 - 1);
  55275. for (frame = start; frame >= 0; frame--) {
  55276. if (offsets[frame] <= t) {
  55277. break;
  55278. }
  55279. }
  55280. // PENDING really need to do this ?
  55281. frame = Math.min(frame, len$$1 - 2);
  55282. }
  55283. else {
  55284. for (var frame = lastFrame; frame < len$$1; frame++) {
  55285. if (offsets[frame] > t) {
  55286. break;
  55287. }
  55288. }
  55289. frame = Math.min(frame - 1, len$$1 - 2);
  55290. }
  55291. lerp(
  55292. symbol.position, points[frame], points[frame + 1],
  55293. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  55294. );
  55295. var tx = points[frame + 1][0] - points[frame][0];
  55296. var ty = points[frame + 1][1] - points[frame][1];
  55297. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  55298. this._lastFrame = frame;
  55299. this._lastFramePercent = t;
  55300. symbol.ignore = false;
  55301. };
  55302. inherits(EffectPolyline, EffectLine);
  55303. /*
  55304. * Licensed to the Apache Software Foundation (ASF) under one
  55305. * or more contributor license agreements. See the NOTICE file
  55306. * distributed with this work for additional information
  55307. * regarding copyright ownership. The ASF licenses this file
  55308. * to you under the Apache License, Version 2.0 (the
  55309. * "License"); you may not use this file except in compliance
  55310. * with the License. You may obtain a copy of the License at
  55311. *
  55312. * http://www.apache.org/licenses/LICENSE-2.0
  55313. *
  55314. * Unless required by applicable law or agreed to in writing,
  55315. * software distributed under the License is distributed on an
  55316. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55317. * KIND, either express or implied. See the License for the
  55318. * specific language governing permissions and limitations
  55319. * under the License.
  55320. */
  55321. // TODO Batch by color
  55322. var LargeLineShape = extendShape({
  55323. shape: {
  55324. polyline: false,
  55325. curveness: 0,
  55326. segs: []
  55327. },
  55328. buildPath: function (path, shape) {
  55329. var segs = shape.segs;
  55330. var curveness = shape.curveness;
  55331. if (shape.polyline) {
  55332. for (var i = 0; i < segs.length;) {
  55333. var count = segs[i++];
  55334. if (count > 0) {
  55335. path.moveTo(segs[i++], segs[i++]);
  55336. for (var k = 1; k < count; k++) {
  55337. path.lineTo(segs[i++], segs[i++]);
  55338. }
  55339. }
  55340. }
  55341. }
  55342. else {
  55343. for (var i = 0; i < segs.length;) {
  55344. var x0 = segs[i++];
  55345. var y0 = segs[i++];
  55346. var x1 = segs[i++];
  55347. var y1 = segs[i++];
  55348. path.moveTo(x0, y0);
  55349. if (curveness > 0) {
  55350. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  55351. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  55352. path.quadraticCurveTo(x2, y2, x1, y1);
  55353. }
  55354. else {
  55355. path.lineTo(x1, y1);
  55356. }
  55357. }
  55358. }
  55359. },
  55360. findDataIndex: function (x, y) {
  55361. var shape = this.shape;
  55362. var segs = shape.segs;
  55363. var curveness = shape.curveness;
  55364. if (shape.polyline) {
  55365. var dataIndex = 0;
  55366. for (var i = 0; i < segs.length;) {
  55367. var count = segs[i++];
  55368. if (count > 0) {
  55369. var x0 = segs[i++];
  55370. var y0 = segs[i++];
  55371. for (var k = 1; k < count; k++) {
  55372. var x1 = segs[i++];
  55373. var y1 = segs[i++];
  55374. if (containStroke$1(x0, y0, x1, y1)) {
  55375. return dataIndex;
  55376. }
  55377. }
  55378. }
  55379. dataIndex++;
  55380. }
  55381. }
  55382. else {
  55383. var dataIndex = 0;
  55384. for (var i = 0; i < segs.length;) {
  55385. var x0 = segs[i++];
  55386. var y0 = segs[i++];
  55387. var x1 = segs[i++];
  55388. var y1 = segs[i++];
  55389. if (curveness > 0) {
  55390. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  55391. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  55392. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  55393. return dataIndex;
  55394. }
  55395. }
  55396. else {
  55397. if (containStroke$1(x0, y0, x1, y1)) {
  55398. return dataIndex;
  55399. }
  55400. }
  55401. dataIndex++;
  55402. }
  55403. }
  55404. return -1;
  55405. }
  55406. });
  55407. function LargeLineDraw() {
  55408. this.group = new Group();
  55409. }
  55410. var largeLineProto = LargeLineDraw.prototype;
  55411. largeLineProto.isPersistent = function () {
  55412. return !this._incremental;
  55413. };
  55414. /**
  55415. * Update symbols draw by new data
  55416. * @param {module:echarts/data/List} data
  55417. */
  55418. largeLineProto.updateData = function (data) {
  55419. this.group.removeAll();
  55420. var lineEl = new LargeLineShape({
  55421. rectHover: true,
  55422. cursor: 'default'
  55423. });
  55424. lineEl.setShape({
  55425. segs: data.getLayout('linesPoints')
  55426. });
  55427. this._setCommon(lineEl, data);
  55428. // Add back
  55429. this.group.add(lineEl);
  55430. this._incremental = null;
  55431. };
  55432. /**
  55433. * @override
  55434. */
  55435. largeLineProto.incrementalPrepareUpdate = function (data) {
  55436. this.group.removeAll();
  55437. this._clearIncremental();
  55438. if (data.count() > 5e5) {
  55439. if (!this._incremental) {
  55440. this._incremental = new IncrementalDisplayble({
  55441. silent: true
  55442. });
  55443. }
  55444. this.group.add(this._incremental);
  55445. }
  55446. else {
  55447. this._incremental = null;
  55448. }
  55449. };
  55450. /**
  55451. * @override
  55452. */
  55453. largeLineProto.incrementalUpdate = function (taskParams, data) {
  55454. var lineEl = new LargeLineShape();
  55455. lineEl.setShape({
  55456. segs: data.getLayout('linesPoints')
  55457. });
  55458. this._setCommon(lineEl, data, !!this._incremental);
  55459. if (!this._incremental) {
  55460. lineEl.rectHover = true;
  55461. lineEl.cursor = 'default';
  55462. lineEl.__startIndex = taskParams.start;
  55463. this.group.add(lineEl);
  55464. }
  55465. else {
  55466. this._incremental.addDisplayable(lineEl, true);
  55467. }
  55468. };
  55469. /**
  55470. * @override
  55471. */
  55472. largeLineProto.remove = function () {
  55473. this._clearIncremental();
  55474. this._incremental = null;
  55475. this.group.removeAll();
  55476. };
  55477. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  55478. var hostModel = data.hostModel;
  55479. lineEl.setShape({
  55480. polyline: hostModel.get('polyline'),
  55481. curveness: hostModel.get('lineStyle.curveness')
  55482. });
  55483. lineEl.useStyle(
  55484. hostModel.getModel('lineStyle').getLineStyle()
  55485. );
  55486. lineEl.style.strokeNoScale = true;
  55487. var visualColor = data.getVisual('color');
  55488. if (visualColor) {
  55489. lineEl.setStyle('stroke', visualColor);
  55490. }
  55491. lineEl.setStyle('fill');
  55492. if (!isIncremental) {
  55493. // Enable tooltip
  55494. // PENDING May have performance issue when path is extremely large
  55495. lineEl.seriesIndex = hostModel.seriesIndex;
  55496. lineEl.on('mousemove', function (e) {
  55497. lineEl.dataIndex = null;
  55498. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  55499. if (dataIndex > 0) {
  55500. // Provide dataIndex for tooltip
  55501. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  55502. }
  55503. });
  55504. }
  55505. };
  55506. largeLineProto._clearIncremental = function () {
  55507. var incremental = this._incremental;
  55508. if (incremental) {
  55509. incremental.clearDisplaybles();
  55510. }
  55511. };
  55512. /*
  55513. * Licensed to the Apache Software Foundation (ASF) under one
  55514. * or more contributor license agreements. See the NOTICE file
  55515. * distributed with this work for additional information
  55516. * regarding copyright ownership. The ASF licenses this file
  55517. * to you under the Apache License, Version 2.0 (the
  55518. * "License"); you may not use this file except in compliance
  55519. * with the License. You may obtain a copy of the License at
  55520. *
  55521. * http://www.apache.org/licenses/LICENSE-2.0
  55522. *
  55523. * Unless required by applicable law or agreed to in writing,
  55524. * software distributed under the License is distributed on an
  55525. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55526. * KIND, either express or implied. See the License for the
  55527. * specific language governing permissions and limitations
  55528. * under the License.
  55529. */
  55530. /* global Float32Array */
  55531. var linesLayout = {
  55532. seriesType: 'lines',
  55533. plan: createRenderPlanner(),
  55534. reset: function (seriesModel) {
  55535. var coordSys = seriesModel.coordinateSystem;
  55536. var isPolyline = seriesModel.get('polyline');
  55537. var isLarge = seriesModel.pipelineContext.large;
  55538. function progress(params, lineData) {
  55539. var lineCoords = [];
  55540. if (isLarge) {
  55541. var points;
  55542. var segCount = params.end - params.start;
  55543. if (isPolyline) {
  55544. var totalCoordsCount = 0;
  55545. for (var i = params.start; i < params.end; i++) {
  55546. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  55547. }
  55548. points = new Float32Array(segCount + totalCoordsCount * 2);
  55549. }
  55550. else {
  55551. points = new Float32Array(segCount * 4);
  55552. }
  55553. var offset = 0;
  55554. var pt = [];
  55555. for (var i = params.start; i < params.end; i++) {
  55556. var len = seriesModel.getLineCoords(i, lineCoords);
  55557. if (isPolyline) {
  55558. points[offset++] = len;
  55559. }
  55560. for (var k = 0; k < len; k++) {
  55561. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  55562. points[offset++] = pt[0];
  55563. points[offset++] = pt[1];
  55564. }
  55565. }
  55566. lineData.setLayout('linesPoints', points);
  55567. }
  55568. else {
  55569. for (var i = params.start; i < params.end; i++) {
  55570. var itemModel = lineData.getItemModel(i);
  55571. var len = seriesModel.getLineCoords(i, lineCoords);
  55572. var pts = [];
  55573. if (isPolyline) {
  55574. for (var j = 0; j < len; j++) {
  55575. pts.push(coordSys.dataToPoint(lineCoords[j]));
  55576. }
  55577. }
  55578. else {
  55579. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  55580. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  55581. var curveness = itemModel.get('lineStyle.curveness');
  55582. if (+curveness) {
  55583. pts[2] = [
  55584. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  55585. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  55586. ];
  55587. }
  55588. }
  55589. lineData.setItemLayout(i, pts);
  55590. }
  55591. }
  55592. }
  55593. return { progress: progress };
  55594. }
  55595. };
  55596. /*
  55597. * Licensed to the Apache Software Foundation (ASF) under one
  55598. * or more contributor license agreements. See the NOTICE file
  55599. * distributed with this work for additional information
  55600. * regarding copyright ownership. The ASF licenses this file
  55601. * to you under the Apache License, Version 2.0 (the
  55602. * "License"); you may not use this file except in compliance
  55603. * with the License. You may obtain a copy of the License at
  55604. *
  55605. * http://www.apache.org/licenses/LICENSE-2.0
  55606. *
  55607. * Unless required by applicable law or agreed to in writing,
  55608. * software distributed under the License is distributed on an
  55609. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55610. * KIND, either express or implied. See the License for the
  55611. * specific language governing permissions and limitations
  55612. * under the License.
  55613. */
  55614. extendChartView({
  55615. type: 'lines',
  55616. init: function () {},
  55617. render: function (seriesModel, ecModel, api) {
  55618. var data = seriesModel.getData();
  55619. var lineDraw = this._updateLineDraw(data, seriesModel);
  55620. var zlevel = seriesModel.get('zlevel');
  55621. var trailLength = seriesModel.get('effect.trailLength');
  55622. var zr = api.getZr();
  55623. // Avoid the drag cause ghost shadow
  55624. // FIXME Better way ?
  55625. // SVG doesn't support
  55626. var isSvg = zr.painter.getType() === 'svg';
  55627. if (!isSvg) {
  55628. zr.painter.getLayer(zlevel).clear(true);
  55629. }
  55630. // Config layer with motion blur
  55631. if (this._lastZlevel != null && !isSvg) {
  55632. zr.configLayer(this._lastZlevel, {
  55633. motionBlur: false
  55634. });
  55635. }
  55636. if (this._showEffect(seriesModel) && trailLength) {
  55637. if (__DEV__) {
  55638. var notInIndividual = false;
  55639. ecModel.eachSeries(function (otherSeriesModel) {
  55640. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  55641. notInIndividual = true;
  55642. }
  55643. });
  55644. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  55645. }
  55646. if (!isSvg) {
  55647. zr.configLayer(zlevel, {
  55648. motionBlur: true,
  55649. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  55650. });
  55651. }
  55652. }
  55653. lineDraw.updateData(data);
  55654. this._lastZlevel = zlevel;
  55655. this._finished = true;
  55656. },
  55657. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  55658. var data = seriesModel.getData();
  55659. var lineDraw = this._updateLineDraw(data, seriesModel);
  55660. lineDraw.incrementalPrepareUpdate(data);
  55661. this._clearLayer(api);
  55662. this._finished = false;
  55663. },
  55664. incrementalRender: function (taskParams, seriesModel, ecModel) {
  55665. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  55666. this._finished = taskParams.end === seriesModel.getData().count();
  55667. },
  55668. updateTransform: function (seriesModel, ecModel, api) {
  55669. var data = seriesModel.getData();
  55670. var pipelineContext = seriesModel.pipelineContext;
  55671. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  55672. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  55673. return {
  55674. update: true
  55675. };
  55676. }
  55677. else {
  55678. // TODO Use same logic with ScatterView.
  55679. // Manually update layout
  55680. var res = linesLayout.reset(seriesModel);
  55681. if (res.progress) {
  55682. res.progress({ start: 0, end: data.count() }, data);
  55683. }
  55684. this._lineDraw.updateLayout();
  55685. this._clearLayer(api);
  55686. }
  55687. },
  55688. _updateLineDraw: function (data, seriesModel) {
  55689. var lineDraw = this._lineDraw;
  55690. var hasEffect = this._showEffect(seriesModel);
  55691. var isPolyline = !!seriesModel.get('polyline');
  55692. var pipelineContext = seriesModel.pipelineContext;
  55693. var isLargeDraw = pipelineContext.large;
  55694. if (__DEV__) {
  55695. if (hasEffect && isLargeDraw) {
  55696. console.warn('Large lines not support effect');
  55697. }
  55698. }
  55699. if (!lineDraw
  55700. || hasEffect !== this._hasEffet
  55701. || isPolyline !== this._isPolyline
  55702. || isLargeDraw !== this._isLargeDraw
  55703. ) {
  55704. if (lineDraw) {
  55705. lineDraw.remove();
  55706. }
  55707. lineDraw = this._lineDraw = isLargeDraw
  55708. ? new LargeLineDraw()
  55709. : new LineDraw(
  55710. isPolyline
  55711. ? (hasEffect ? EffectPolyline : Polyline$2)
  55712. : (hasEffect ? EffectLine : Line$1)
  55713. );
  55714. this._hasEffet = hasEffect;
  55715. this._isPolyline = isPolyline;
  55716. this._isLargeDraw = isLargeDraw;
  55717. this.group.removeAll();
  55718. }
  55719. this.group.add(lineDraw.group);
  55720. return lineDraw;
  55721. },
  55722. _showEffect: function (seriesModel) {
  55723. return !!seriesModel.get('effect.show');
  55724. },
  55725. _clearLayer: function (api) {
  55726. // Not use motion when dragging or zooming
  55727. var zr = api.getZr();
  55728. var isSvg = zr.painter.getType() === 'svg';
  55729. if (!isSvg && this._lastZlevel != null) {
  55730. zr.painter.getLayer(this._lastZlevel).clear(true);
  55731. }
  55732. },
  55733. remove: function (ecModel, api) {
  55734. this._lineDraw && this._lineDraw.remove();
  55735. this._lineDraw = null;
  55736. // Clear motion when lineDraw is removed
  55737. this._clearLayer(api);
  55738. },
  55739. dispose: function () {}
  55740. });
  55741. /*
  55742. * Licensed to the Apache Software Foundation (ASF) under one
  55743. * or more contributor license agreements. See the NOTICE file
  55744. * distributed with this work for additional information
  55745. * regarding copyright ownership. The ASF licenses this file
  55746. * to you under the Apache License, Version 2.0 (the
  55747. * "License"); you may not use this file except in compliance
  55748. * with the License. You may obtain a copy of the License at
  55749. *
  55750. * http://www.apache.org/licenses/LICENSE-2.0
  55751. *
  55752. * Unless required by applicable law or agreed to in writing,
  55753. * software distributed under the License is distributed on an
  55754. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55755. * KIND, either express or implied. See the License for the
  55756. * specific language governing permissions and limitations
  55757. * under the License.
  55758. */
  55759. function normalize$2(a) {
  55760. if (!(a instanceof Array)) {
  55761. a = [a, a];
  55762. }
  55763. return a;
  55764. }
  55765. var opacityQuery = 'lineStyle.opacity'.split('.');
  55766. var linesVisual = {
  55767. seriesType: 'lines',
  55768. reset: function (seriesModel, ecModel, api) {
  55769. var symbolType = normalize$2(seriesModel.get('symbol'));
  55770. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  55771. var data = seriesModel.getData();
  55772. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  55773. data.setVisual('toSymbol', symbolType && symbolType[1]);
  55774. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  55775. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  55776. data.setVisual('opacity', seriesModel.get(opacityQuery));
  55777. function dataEach(data, idx) {
  55778. var itemModel = data.getItemModel(idx);
  55779. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  55780. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  55781. var opacity = itemModel.get(opacityQuery);
  55782. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  55783. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  55784. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  55785. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  55786. data.setItemVisual(idx, 'opacity', opacity);
  55787. }
  55788. return {dataEach: data.hasItemOption ? dataEach : null};
  55789. }
  55790. };
  55791. /*
  55792. * Licensed to the Apache Software Foundation (ASF) under one
  55793. * or more contributor license agreements. See the NOTICE file
  55794. * distributed with this work for additional information
  55795. * regarding copyright ownership. The ASF licenses this file
  55796. * to you under the Apache License, Version 2.0 (the
  55797. * "License"); you may not use this file except in compliance
  55798. * with the License. You may obtain a copy of the License at
  55799. *
  55800. * http://www.apache.org/licenses/LICENSE-2.0
  55801. *
  55802. * Unless required by applicable law or agreed to in writing,
  55803. * software distributed under the License is distributed on an
  55804. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55805. * KIND, either express or implied. See the License for the
  55806. * specific language governing permissions and limitations
  55807. * under the License.
  55808. */
  55809. registerLayout(linesLayout);
  55810. registerVisual(linesVisual);
  55811. /*
  55812. * Licensed to the Apache Software Foundation (ASF) under one
  55813. * or more contributor license agreements. See the NOTICE file
  55814. * distributed with this work for additional information
  55815. * regarding copyright ownership. The ASF licenses this file
  55816. * to you under the Apache License, Version 2.0 (the
  55817. * "License"); you may not use this file except in compliance
  55818. * with the License. You may obtain a copy of the License at
  55819. *
  55820. * http://www.apache.org/licenses/LICENSE-2.0
  55821. *
  55822. * Unless required by applicable law or agreed to in writing,
  55823. * software distributed under the License is distributed on an
  55824. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55825. * KIND, either express or implied. See the License for the
  55826. * specific language governing permissions and limitations
  55827. * under the License.
  55828. */
  55829. SeriesModel.extend({
  55830. type: 'series.heatmap',
  55831. getInitialData: function (option, ecModel) {
  55832. return createListFromArray(this.getSource(), this, {
  55833. generateCoord: 'value'
  55834. });
  55835. },
  55836. preventIncremental: function () {
  55837. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  55838. if (coordSysCreator && coordSysCreator.dimensions) {
  55839. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  55840. }
  55841. },
  55842. defaultOption: {
  55843. // Cartesian2D or geo
  55844. coordinateSystem: 'cartesian2d',
  55845. zlevel: 0,
  55846. z: 2,
  55847. // Cartesian coordinate system
  55848. // xAxisIndex: 0,
  55849. // yAxisIndex: 0,
  55850. // Geo coordinate system
  55851. geoIndex: 0,
  55852. blurSize: 30,
  55853. pointSize: 20,
  55854. maxOpacity: 1,
  55855. minOpacity: 0
  55856. }
  55857. });
  55858. /*
  55859. * Licensed to the Apache Software Foundation (ASF) under one
  55860. * or more contributor license agreements. See the NOTICE file
  55861. * distributed with this work for additional information
  55862. * regarding copyright ownership. The ASF licenses this file
  55863. * to you under the Apache License, Version 2.0 (the
  55864. * "License"); you may not use this file except in compliance
  55865. * with the License. You may obtain a copy of the License at
  55866. *
  55867. * http://www.apache.org/licenses/LICENSE-2.0
  55868. *
  55869. * Unless required by applicable law or agreed to in writing,
  55870. * software distributed under the License is distributed on an
  55871. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55872. * KIND, either express or implied. See the License for the
  55873. * specific language governing permissions and limitations
  55874. * under the License.
  55875. */
  55876. /* global Uint8ClampedArray */
  55877. /**
  55878. * @file defines echarts Heatmap Chart
  55879. * @author Ovilia (me@zhangwenli.com)
  55880. * Inspired by https://github.com/mourner/simpleheat
  55881. *
  55882. * @module
  55883. */
  55884. var GRADIENT_LEVELS = 256;
  55885. /**
  55886. * Heatmap Chart
  55887. *
  55888. * @class
  55889. */
  55890. function Heatmap() {
  55891. var canvas = createCanvas();
  55892. this.canvas = canvas;
  55893. this.blurSize = 30;
  55894. this.pointSize = 20;
  55895. this.maxOpacity = 1;
  55896. this.minOpacity = 0;
  55897. this._gradientPixels = {};
  55898. }
  55899. Heatmap.prototype = {
  55900. /**
  55901. * Renders Heatmap and returns the rendered canvas
  55902. * @param {Array} data array of data, each has x, y, value
  55903. * @param {number} width canvas width
  55904. * @param {number} height canvas height
  55905. */
  55906. update: function (data, width, height, normalize, colorFunc, isInRange) {
  55907. var brush = this._getBrush();
  55908. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  55909. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  55910. var r = this.pointSize + this.blurSize;
  55911. var canvas = this.canvas;
  55912. var ctx = canvas.getContext('2d');
  55913. var len = data.length;
  55914. canvas.width = width;
  55915. canvas.height = height;
  55916. for (var i = 0; i < len; ++i) {
  55917. var p = data[i];
  55918. var x = p[0];
  55919. var y = p[1];
  55920. var value = p[2];
  55921. // calculate alpha using value
  55922. var alpha = normalize(value);
  55923. // draw with the circle brush with alpha
  55924. ctx.globalAlpha = alpha;
  55925. ctx.drawImage(brush, x - r, y - r);
  55926. }
  55927. if (!canvas.width || !canvas.height) {
  55928. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  55929. // 'CanvasRenderingContext2D': The source height is 0."
  55930. return canvas;
  55931. }
  55932. // colorize the canvas using alpha value and set with gradient
  55933. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  55934. var pixels = imageData.data;
  55935. var offset = 0;
  55936. var pixelLen = pixels.length;
  55937. var minOpacity = this.minOpacity;
  55938. var maxOpacity = this.maxOpacity;
  55939. var diffOpacity = maxOpacity - minOpacity;
  55940. while (offset < pixelLen) {
  55941. var alpha = pixels[offset + 3] / 256;
  55942. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  55943. // Simple optimize to ignore the empty data
  55944. if (alpha > 0) {
  55945. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  55946. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  55947. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  55948. pixels[offset++] = gradient[gradientOffset];
  55949. pixels[offset++] = gradient[gradientOffset + 1];
  55950. pixels[offset++] = gradient[gradientOffset + 2];
  55951. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  55952. }
  55953. else {
  55954. offset += 4;
  55955. }
  55956. }
  55957. ctx.putImageData(imageData, 0, 0);
  55958. return canvas;
  55959. },
  55960. /**
  55961. * get canvas of a black circle brush used for canvas to draw later
  55962. * @private
  55963. * @returns {Object} circle brush canvas
  55964. */
  55965. _getBrush: function () {
  55966. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  55967. // set brush size
  55968. var r = this.pointSize + this.blurSize;
  55969. var d = r * 2;
  55970. brushCanvas.width = d;
  55971. brushCanvas.height = d;
  55972. var ctx = brushCanvas.getContext('2d');
  55973. ctx.clearRect(0, 0, d, d);
  55974. // in order to render shadow without the distinct circle,
  55975. // draw the distinct circle in an invisible place,
  55976. // and use shadowOffset to draw shadow in the center of the canvas
  55977. ctx.shadowOffsetX = d;
  55978. ctx.shadowBlur = this.blurSize;
  55979. // draw the shadow in black, and use alpha and shadow blur to generate
  55980. // color in color map
  55981. ctx.shadowColor = '#000';
  55982. // draw circle in the left to the canvas
  55983. ctx.beginPath();
  55984. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  55985. ctx.closePath();
  55986. ctx.fill();
  55987. return brushCanvas;
  55988. },
  55989. /**
  55990. * get gradient color map
  55991. * @private
  55992. */
  55993. _getGradient: function (data, colorFunc, state) {
  55994. var gradientPixels = this._gradientPixels;
  55995. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  55996. var color = [0, 0, 0, 0];
  55997. var off = 0;
  55998. for (var i = 0; i < 256; i++) {
  55999. colorFunc[state](i / 255, true, color);
  56000. pixelsSingleState[off++] = color[0];
  56001. pixelsSingleState[off++] = color[1];
  56002. pixelsSingleState[off++] = color[2];
  56003. pixelsSingleState[off++] = color[3];
  56004. }
  56005. return pixelsSingleState;
  56006. }
  56007. };
  56008. /*
  56009. * Licensed to the Apache Software Foundation (ASF) under one
  56010. * or more contributor license agreements. See the NOTICE file
  56011. * distributed with this work for additional information
  56012. * regarding copyright ownership. The ASF licenses this file
  56013. * to you under the Apache License, Version 2.0 (the
  56014. * "License"); you may not use this file except in compliance
  56015. * with the License. You may obtain a copy of the License at
  56016. *
  56017. * http://www.apache.org/licenses/LICENSE-2.0
  56018. *
  56019. * Unless required by applicable law or agreed to in writing,
  56020. * software distributed under the License is distributed on an
  56021. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56022. * KIND, either express or implied. See the License for the
  56023. * specific language governing permissions and limitations
  56024. * under the License.
  56025. */
  56026. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  56027. var dataSpan = dataExtent[1] - dataExtent[0];
  56028. pieceList = map(pieceList, function (piece) {
  56029. return {
  56030. interval: [
  56031. (piece.interval[0] - dataExtent[0]) / dataSpan,
  56032. (piece.interval[1] - dataExtent[0]) / dataSpan
  56033. ]
  56034. };
  56035. });
  56036. var len = pieceList.length;
  56037. var lastIndex = 0;
  56038. return function (val) {
  56039. // Try to find in the location of the last found
  56040. for (var i = lastIndex; i < len; i++) {
  56041. var interval = pieceList[i].interval;
  56042. if (interval[0] <= val && val <= interval[1]) {
  56043. lastIndex = i;
  56044. break;
  56045. }
  56046. }
  56047. if (i === len) { // Not found, back interation
  56048. for (var i = lastIndex - 1; i >= 0; i--) {
  56049. var interval = pieceList[i].interval;
  56050. if (interval[0] <= val && val <= interval[1]) {
  56051. lastIndex = i;
  56052. break;
  56053. }
  56054. }
  56055. }
  56056. return i >= 0 && i < len && selected[i];
  56057. };
  56058. }
  56059. function getIsInContinuousRange(dataExtent, range) {
  56060. var dataSpan = dataExtent[1] - dataExtent[0];
  56061. range = [
  56062. (range[0] - dataExtent[0]) / dataSpan,
  56063. (range[1] - dataExtent[0]) / dataSpan
  56064. ];
  56065. return function (val) {
  56066. return val >= range[0] && val <= range[1];
  56067. };
  56068. }
  56069. function isGeoCoordSys(coordSys) {
  56070. var dimensions = coordSys.dimensions;
  56071. // Not use coorSys.type === 'geo' because coordSys maybe extended
  56072. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  56073. }
  56074. extendChartView({
  56075. type: 'heatmap',
  56076. render: function (seriesModel, ecModel, api) {
  56077. var visualMapOfThisSeries;
  56078. ecModel.eachComponent('visualMap', function (visualMap) {
  56079. visualMap.eachTargetSeries(function (targetSeries) {
  56080. if (targetSeries === seriesModel) {
  56081. visualMapOfThisSeries = visualMap;
  56082. }
  56083. });
  56084. });
  56085. if (__DEV__) {
  56086. if (!visualMapOfThisSeries) {
  56087. throw new Error('Heatmap must use with visualMap');
  56088. }
  56089. }
  56090. this.group.removeAll();
  56091. this._incrementalDisplayable = null;
  56092. var coordSys = seriesModel.coordinateSystem;
  56093. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  56094. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  56095. }
  56096. else if (isGeoCoordSys(coordSys)) {
  56097. this._renderOnGeo(
  56098. coordSys, seriesModel, visualMapOfThisSeries, api
  56099. );
  56100. }
  56101. },
  56102. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  56103. this.group.removeAll();
  56104. },
  56105. incrementalRender: function (params, seriesModel, ecModel, api) {
  56106. var coordSys = seriesModel.coordinateSystem;
  56107. if (coordSys) {
  56108. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  56109. }
  56110. },
  56111. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  56112. var coordSys = seriesModel.coordinateSystem;
  56113. var width;
  56114. var height;
  56115. if (coordSys.type === 'cartesian2d') {
  56116. var xAxis = coordSys.getAxis('x');
  56117. var yAxis = coordSys.getAxis('y');
  56118. if (__DEV__) {
  56119. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  56120. throw new Error('Heatmap on cartesian must have two category axes');
  56121. }
  56122. if (!(xAxis.onBand && yAxis.onBand)) {
  56123. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  56124. }
  56125. }
  56126. width = xAxis.getBandWidth();
  56127. height = yAxis.getBandWidth();
  56128. }
  56129. var group = this.group;
  56130. var data = seriesModel.getData();
  56131. var itemStyleQuery = 'itemStyle';
  56132. var hoverItemStyleQuery = 'emphasis.itemStyle';
  56133. var labelQuery = 'label';
  56134. var hoverLabelQuery = 'emphasis.label';
  56135. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  56136. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  56137. var labelModel = seriesModel.getModel(labelQuery);
  56138. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  56139. var coordSysType = coordSys.type;
  56140. var dataDims = coordSysType === 'cartesian2d'
  56141. ? [
  56142. data.mapDimension('x'),
  56143. data.mapDimension('y'),
  56144. data.mapDimension('value')
  56145. ]
  56146. : [
  56147. data.mapDimension('time'),
  56148. data.mapDimension('value')
  56149. ];
  56150. for (var idx = start; idx < end; idx++) {
  56151. var rect;
  56152. if (coordSysType === 'cartesian2d') {
  56153. // Ignore empty data
  56154. if (isNaN(data.get(dataDims[2], idx))) {
  56155. continue;
  56156. }
  56157. var point = coordSys.dataToPoint([
  56158. data.get(dataDims[0], idx),
  56159. data.get(dataDims[1], idx)
  56160. ]);
  56161. rect = new Rect({
  56162. shape: {
  56163. x: point[0] - width / 2,
  56164. y: point[1] - height / 2,
  56165. width: width,
  56166. height: height
  56167. },
  56168. style: {
  56169. fill: data.getItemVisual(idx, 'color'),
  56170. opacity: data.getItemVisual(idx, 'opacity')
  56171. }
  56172. });
  56173. }
  56174. else {
  56175. // Ignore empty data
  56176. if (isNaN(data.get(dataDims[1], idx))) {
  56177. continue;
  56178. }
  56179. rect = new Rect({
  56180. z2: 1,
  56181. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  56182. style: {
  56183. fill: data.getItemVisual(idx, 'color'),
  56184. opacity: data.getItemVisual(idx, 'opacity')
  56185. }
  56186. });
  56187. }
  56188. var itemModel = data.getItemModel(idx);
  56189. // Optimization for large datset
  56190. if (data.hasItemOption) {
  56191. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  56192. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  56193. labelModel = itemModel.getModel(labelQuery);
  56194. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  56195. }
  56196. var rawValue = seriesModel.getRawValue(idx);
  56197. var defaultText = '-';
  56198. if (rawValue && rawValue[2] != null) {
  56199. defaultText = rawValue[2];
  56200. }
  56201. setLabelStyle(
  56202. style, hoverStl, labelModel, hoverLabelModel,
  56203. {
  56204. labelFetcher: seriesModel,
  56205. labelDataIndex: idx,
  56206. defaultText: defaultText,
  56207. isRectText: true
  56208. }
  56209. );
  56210. rect.setStyle(style);
  56211. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  56212. rect.incremental = incremental;
  56213. // PENDING
  56214. if (incremental) {
  56215. // Rect must use hover layer if it's incremental.
  56216. rect.useHoverLayer = true;
  56217. }
  56218. group.add(rect);
  56219. data.setItemGraphicEl(idx, rect);
  56220. }
  56221. },
  56222. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  56223. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  56224. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  56225. // if (!visualMapping) {
  56226. // throw new Error('Data range must have color visuals');
  56227. // }
  56228. var data = seriesModel.getData();
  56229. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  56230. hmLayer.blurSize = seriesModel.get('blurSize');
  56231. hmLayer.pointSize = seriesModel.get('pointSize');
  56232. hmLayer.minOpacity = seriesModel.get('minOpacity');
  56233. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  56234. var rect = geo.getViewRect().clone();
  56235. var roamTransform = geo.getRoamTransform();
  56236. rect.applyTransform(roamTransform);
  56237. // Clamp on viewport
  56238. var x = Math.max(rect.x, 0);
  56239. var y = Math.max(rect.y, 0);
  56240. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  56241. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  56242. var width = x2 - x;
  56243. var height = y2 - y;
  56244. var dims = [
  56245. data.mapDimension('lng'),
  56246. data.mapDimension('lat'),
  56247. data.mapDimension('value')
  56248. ];
  56249. var points = data.mapArray(dims, function (lng, lat, value) {
  56250. var pt = geo.dataToPoint([lng, lat]);
  56251. pt[0] -= x;
  56252. pt[1] -= y;
  56253. pt.push(value);
  56254. return pt;
  56255. });
  56256. var dataExtent = visualMapModel.getExtent();
  56257. var isInRange = visualMapModel.type === 'visualMap.continuous'
  56258. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  56259. : getIsInPiecewiseRange(
  56260. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  56261. );
  56262. hmLayer.update(
  56263. points, width, height,
  56264. inRangeVisuals.color.getNormalizer(),
  56265. {
  56266. inRange: inRangeVisuals.color.getColorMapper(),
  56267. outOfRange: outOfRangeVisuals.color.getColorMapper()
  56268. },
  56269. isInRange
  56270. );
  56271. var img = new ZImage({
  56272. style: {
  56273. width: width,
  56274. height: height,
  56275. x: x,
  56276. y: y,
  56277. image: hmLayer.canvas
  56278. },
  56279. silent: true
  56280. });
  56281. this.group.add(img);
  56282. },
  56283. dispose: function () {}
  56284. });
  56285. /*
  56286. * Licensed to the Apache Software Foundation (ASF) under one
  56287. * or more contributor license agreements. See the NOTICE file
  56288. * distributed with this work for additional information
  56289. * regarding copyright ownership. The ASF licenses this file
  56290. * to you under the Apache License, Version 2.0 (the
  56291. * "License"); you may not use this file except in compliance
  56292. * with the License. You may obtain a copy of the License at
  56293. *
  56294. * http://www.apache.org/licenses/LICENSE-2.0
  56295. *
  56296. * Unless required by applicable law or agreed to in writing,
  56297. * software distributed under the License is distributed on an
  56298. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56299. * KIND, either express or implied. See the License for the
  56300. * specific language governing permissions and limitations
  56301. * under the License.
  56302. */
  56303. /*
  56304. * Licensed to the Apache Software Foundation (ASF) under one
  56305. * or more contributor license agreements. See the NOTICE file
  56306. * distributed with this work for additional information
  56307. * regarding copyright ownership. The ASF licenses this file
  56308. * to you under the Apache License, Version 2.0 (the
  56309. * "License"); you may not use this file except in compliance
  56310. * with the License. You may obtain a copy of the License at
  56311. *
  56312. * http://www.apache.org/licenses/LICENSE-2.0
  56313. *
  56314. * Unless required by applicable law or agreed to in writing,
  56315. * software distributed under the License is distributed on an
  56316. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56317. * KIND, either express or implied. See the License for the
  56318. * specific language governing permissions and limitations
  56319. * under the License.
  56320. */
  56321. var PictorialBarSeries = BaseBarSeries.extend({
  56322. type: 'series.pictorialBar',
  56323. dependencies: ['grid'],
  56324. defaultOption: {
  56325. symbol: 'circle', // Customized bar shape
  56326. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  56327. symbolRotate: null,
  56328. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  56329. symbolOffset: null,
  56330. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  56331. // Auto margin by defualt.
  56332. symbolRepeat: false, // false/null/undefined, means no repeat.
  56333. // Can be true, means auto calculate repeat times and cut by data.
  56334. // Can be a number, specifies repeat times, and do not cut by data.
  56335. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  56336. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  56337. symbolClip: false,
  56338. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  56339. symbolPatternSize: 400, // 400 * 400 px
  56340. barGap: '-100%', // In most case, overlap is needed.
  56341. // z can be set in data item, which is z2 actually.
  56342. // Disable progressive
  56343. progressive: 0,
  56344. hoverAnimation: false // Open only when needed.
  56345. },
  56346. getInitialData: function (option) {
  56347. // Disable stack.
  56348. option.stack = null;
  56349. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  56350. }
  56351. });
  56352. /*
  56353. * Licensed to the Apache Software Foundation (ASF) under one
  56354. * or more contributor license agreements. See the NOTICE file
  56355. * distributed with this work for additional information
  56356. * regarding copyright ownership. The ASF licenses this file
  56357. * to you under the Apache License, Version 2.0 (the
  56358. * "License"); you may not use this file except in compliance
  56359. * with the License. You may obtain a copy of the License at
  56360. *
  56361. * http://www.apache.org/licenses/LICENSE-2.0
  56362. *
  56363. * Unless required by applicable law or agreed to in writing,
  56364. * software distributed under the License is distributed on an
  56365. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56366. * KIND, either express or implied. See the License for the
  56367. * specific language governing permissions and limitations
  56368. * under the License.
  56369. */
  56370. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth'];
  56371. // index: +isHorizontal
  56372. var LAYOUT_ATTRS = [
  56373. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  56374. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  56375. ];
  56376. var pathForLineWidth = new Circle();
  56377. var BarView$1 = extendChartView({
  56378. type: 'pictorialBar',
  56379. render: function (seriesModel, ecModel, api) {
  56380. var group = this.group;
  56381. var data = seriesModel.getData();
  56382. var oldData = this._data;
  56383. var cartesian = seriesModel.coordinateSystem;
  56384. var baseAxis = cartesian.getBaseAxis();
  56385. var isHorizontal = !!baseAxis.isHorizontal();
  56386. var coordSysRect = cartesian.grid.getRect();
  56387. var opt = {
  56388. ecSize: {width: api.getWidth(), height: api.getHeight()},
  56389. seriesModel: seriesModel,
  56390. coordSys: cartesian,
  56391. coordSysExtent: [
  56392. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  56393. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  56394. ],
  56395. isHorizontal: isHorizontal,
  56396. valueDim: LAYOUT_ATTRS[+isHorizontal],
  56397. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  56398. };
  56399. data.diff(oldData)
  56400. .add(function (dataIndex) {
  56401. if (!data.hasValue(dataIndex)) {
  56402. return;
  56403. }
  56404. var itemModel = getItemModel(data, dataIndex);
  56405. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  56406. var bar = createBar(data, opt, symbolMeta);
  56407. data.setItemGraphicEl(dataIndex, bar);
  56408. group.add(bar);
  56409. updateCommon$1(bar, opt, symbolMeta);
  56410. })
  56411. .update(function (newIndex, oldIndex) {
  56412. var bar = oldData.getItemGraphicEl(oldIndex);
  56413. if (!data.hasValue(newIndex)) {
  56414. group.remove(bar);
  56415. return;
  56416. }
  56417. var itemModel = getItemModel(data, newIndex);
  56418. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  56419. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  56420. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  56421. group.remove(bar);
  56422. data.setItemGraphicEl(newIndex, null);
  56423. bar = null;
  56424. }
  56425. if (bar) {
  56426. updateBar(bar, opt, symbolMeta);
  56427. }
  56428. else {
  56429. bar = createBar(data, opt, symbolMeta, true);
  56430. }
  56431. data.setItemGraphicEl(newIndex, bar);
  56432. bar.__pictorialSymbolMeta = symbolMeta;
  56433. // Add back
  56434. group.add(bar);
  56435. updateCommon$1(bar, opt, symbolMeta);
  56436. })
  56437. .remove(function (dataIndex) {
  56438. var bar = oldData.getItemGraphicEl(dataIndex);
  56439. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  56440. })
  56441. .execute();
  56442. this._data = data;
  56443. return this.group;
  56444. },
  56445. dispose: noop,
  56446. remove: function (ecModel, api) {
  56447. var group = this.group;
  56448. var data = this._data;
  56449. if (ecModel.get('animation')) {
  56450. if (data) {
  56451. data.eachItemGraphicEl(function (bar) {
  56452. removeBar(data, bar.dataIndex, ecModel, bar);
  56453. });
  56454. }
  56455. }
  56456. else {
  56457. group.removeAll();
  56458. }
  56459. }
  56460. });
  56461. // Set or calculate default value about symbol, and calculate layout info.
  56462. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  56463. var layout = data.getItemLayout(dataIndex);
  56464. var symbolRepeat = itemModel.get('symbolRepeat');
  56465. var symbolClip = itemModel.get('symbolClip');
  56466. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  56467. var symbolRotate = itemModel.get('symbolRotate');
  56468. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  56469. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  56470. var isAnimationEnabled = itemModel.isAnimationEnabled();
  56471. var symbolMeta = {
  56472. dataIndex: dataIndex,
  56473. layout: layout,
  56474. itemModel: itemModel,
  56475. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  56476. color: data.getItemVisual(dataIndex, 'color'),
  56477. symbolClip: symbolClip,
  56478. symbolRepeat: symbolRepeat,
  56479. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  56480. symbolPatternSize: symbolPatternSize,
  56481. rotation: rotation,
  56482. animationModel: isAnimationEnabled ? itemModel : null,
  56483. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  56484. z2: itemModel.getShallow('z', true) || 0
  56485. };
  56486. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  56487. prepareSymbolSize(
  56488. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  56489. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  56490. );
  56491. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  56492. var symbolSize = symbolMeta.symbolSize;
  56493. var symbolOffset = itemModel.get('symbolOffset');
  56494. if (isArray(symbolOffset)) {
  56495. symbolOffset = [
  56496. parsePercent$1(symbolOffset[0], symbolSize[0]),
  56497. parsePercent$1(symbolOffset[1], symbolSize[1])
  56498. ];
  56499. }
  56500. prepareLayoutInfo(
  56501. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  56502. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  56503. opt, symbolMeta
  56504. );
  56505. return symbolMeta;
  56506. }
  56507. // bar length can be negative.
  56508. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  56509. var valueDim = opt.valueDim;
  56510. var symbolBoundingData = itemModel.get('symbolBoundingData');
  56511. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  56512. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  56513. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  56514. var boundingLength;
  56515. if (isArray(symbolBoundingData)) {
  56516. var symbolBoundingExtent = [
  56517. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  56518. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  56519. ];
  56520. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  56521. boundingLength = symbolBoundingExtent[pxSignIdx];
  56522. }
  56523. else if (symbolBoundingData != null) {
  56524. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  56525. }
  56526. else if (symbolRepeat) {
  56527. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  56528. }
  56529. else {
  56530. boundingLength = layout[valueDim.wh];
  56531. }
  56532. output.boundingLength = boundingLength;
  56533. if (symbolRepeat) {
  56534. output.repeatCutLength = layout[valueDim.wh];
  56535. }
  56536. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  56537. }
  56538. function convertToCoordOnAxis(axis, value) {
  56539. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  56540. }
  56541. // Support ['100%', '100%']
  56542. function prepareSymbolSize(
  56543. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  56544. pxSign, symbolPatternSize, opt, output
  56545. ) {
  56546. var valueDim = opt.valueDim;
  56547. var categoryDim = opt.categoryDim;
  56548. var categorySize = Math.abs(layout[categoryDim.wh]);
  56549. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  56550. if (isArray(symbolSize)) {
  56551. symbolSize = symbolSize.slice();
  56552. }
  56553. else {
  56554. if (symbolSize == null) {
  56555. symbolSize = '100%';
  56556. }
  56557. symbolSize = [symbolSize, symbolSize];
  56558. }
  56559. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  56560. // to complicated to calculate real percent value if considering scaled lineWidth.
  56561. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  56562. // which can be tolerated in pictorial chart.
  56563. symbolSize[categoryDim.index] = parsePercent$1(
  56564. symbolSize[categoryDim.index],
  56565. categorySize
  56566. );
  56567. symbolSize[valueDim.index] = parsePercent$1(
  56568. symbolSize[valueDim.index],
  56569. symbolRepeat ? categorySize : Math.abs(boundingLength)
  56570. );
  56571. output.symbolSize = symbolSize;
  56572. // If x or y is less than zero, show reversed shape.
  56573. var symbolScale = output.symbolScale = [
  56574. symbolSize[0] / symbolPatternSize,
  56575. symbolSize[1] / symbolPatternSize
  56576. ];
  56577. // Follow convention, 'right' and 'top' is the normal scale.
  56578. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  56579. }
  56580. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  56581. // In symbols are drawn with scale, so do not need to care about the case that width
  56582. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  56583. // be calculated.
  56584. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  56585. if (valueLineWidth) {
  56586. pathForLineWidth.attr({
  56587. scale: symbolScale.slice(),
  56588. rotation: rotation
  56589. });
  56590. pathForLineWidth.updateTransform();
  56591. valueLineWidth /= pathForLineWidth.getLineScale();
  56592. valueLineWidth *= symbolScale[opt.valueDim.index];
  56593. }
  56594. output.valueLineWidth = valueLineWidth;
  56595. }
  56596. function prepareLayoutInfo(
  56597. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  56598. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  56599. ) {
  56600. var categoryDim = opt.categoryDim;
  56601. var valueDim = opt.valueDim;
  56602. var pxSign = output.pxSign;
  56603. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  56604. var pathLen = unitLength;
  56605. // Note: rotation will not effect the layout of symbols, because user may
  56606. // want symbols to rotate on its center, which should not be translated
  56607. // when rotating.
  56608. if (symbolRepeat) {
  56609. var absBoundingLength = Math.abs(boundingLength);
  56610. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  56611. var hasEndGap = false;
  56612. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  56613. hasEndGap = true;
  56614. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  56615. }
  56616. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  56617. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  56618. // When symbol margin is less than 0, margin at both ends will be subtracted
  56619. // to ensure that all of the symbols will not be overflow the given area.
  56620. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  56621. // Both final repeatTimes and final symbolMargin area calculated based on
  56622. // boundingLength.
  56623. var repeatSpecified = isNumeric(symbolRepeat);
  56624. var repeatTimes = repeatSpecified
  56625. ? symbolRepeat
  56626. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  56627. // Adjust calculate margin, to ensure each symbol is displayed
  56628. // entirely in the given layout area.
  56629. var mDiff = absBoundingLength - repeatTimes * unitLength;
  56630. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  56631. uLenWithMargin = unitLength + symbolMargin * 2;
  56632. endFix = hasEndGap ? 0 : symbolMargin * 2;
  56633. // Update repeatTimes when not all symbol will be shown.
  56634. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  56635. repeatTimes = repeatCutLength
  56636. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  56637. : 0;
  56638. }
  56639. pathLen = repeatTimes * uLenWithMargin - endFix;
  56640. output.repeatTimes = repeatTimes;
  56641. output.symbolMargin = symbolMargin;
  56642. }
  56643. var sizeFix = pxSign * (pathLen / 2);
  56644. var pathPosition = output.pathPosition = [];
  56645. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  56646. pathPosition[valueDim.index] = symbolPosition === 'start'
  56647. ? sizeFix
  56648. : symbolPosition === 'end'
  56649. ? boundingLength - sizeFix
  56650. : boundingLength / 2; // 'center'
  56651. if (symbolOffset) {
  56652. pathPosition[0] += symbolOffset[0];
  56653. pathPosition[1] += symbolOffset[1];
  56654. }
  56655. var bundlePosition = output.bundlePosition = [];
  56656. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  56657. bundlePosition[valueDim.index] = layout[valueDim.xy];
  56658. var barRectShape = output.barRectShape = extend({}, layout);
  56659. barRectShape[valueDim.wh] = pxSign * Math.max(
  56660. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  56661. );
  56662. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  56663. var clipShape = output.clipShape = {};
  56664. // Consider that symbol may be overflow layout rect.
  56665. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  56666. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  56667. clipShape[valueDim.xy] = 0;
  56668. clipShape[valueDim.wh] = layout[valueDim.wh];
  56669. }
  56670. function createPath(symbolMeta) {
  56671. var symbolPatternSize = symbolMeta.symbolPatternSize;
  56672. var path = createSymbol(
  56673. // Consider texture img, make a big size.
  56674. symbolMeta.symbolType,
  56675. -symbolPatternSize / 2,
  56676. -symbolPatternSize / 2,
  56677. symbolPatternSize,
  56678. symbolPatternSize,
  56679. symbolMeta.color
  56680. );
  56681. path.attr({
  56682. culling: true
  56683. });
  56684. path.type !== 'image' && path.setStyle({
  56685. strokeNoScale: true
  56686. });
  56687. return path;
  56688. }
  56689. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  56690. var bundle = bar.__pictorialBundle;
  56691. var symbolSize = symbolMeta.symbolSize;
  56692. var valueLineWidth = symbolMeta.valueLineWidth;
  56693. var pathPosition = symbolMeta.pathPosition;
  56694. var valueDim = opt.valueDim;
  56695. var repeatTimes = symbolMeta.repeatTimes || 0;
  56696. var index = 0;
  56697. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  56698. eachPath(bar, function (path) {
  56699. path.__pictorialAnimationIndex = index;
  56700. path.__pictorialRepeatTimes = repeatTimes;
  56701. if (index < repeatTimes) {
  56702. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  56703. }
  56704. else {
  56705. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  56706. bundle.remove(path);
  56707. });
  56708. }
  56709. updateHoverAnimation(path, symbolMeta);
  56710. index++;
  56711. });
  56712. for (; index < repeatTimes; index++) {
  56713. var path = createPath(symbolMeta);
  56714. path.__pictorialAnimationIndex = index;
  56715. path.__pictorialRepeatTimes = repeatTimes;
  56716. bundle.add(path);
  56717. var target = makeTarget(index);
  56718. updateAttr(
  56719. path,
  56720. {
  56721. position: target.position,
  56722. scale: [0, 0]
  56723. },
  56724. {
  56725. scale: target.scale,
  56726. rotation: target.rotation
  56727. },
  56728. symbolMeta,
  56729. isUpdate
  56730. );
  56731. // FIXME
  56732. // If all emphasis/normal through action.
  56733. path
  56734. .on('mouseover', onMouseOver)
  56735. .on('mouseout', onMouseOut);
  56736. updateHoverAnimation(path, symbolMeta);
  56737. }
  56738. function makeTarget(index) {
  56739. var position = pathPosition.slice();
  56740. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  56741. // Otherwise: i = index;
  56742. var pxSign = symbolMeta.pxSign;
  56743. var i = index;
  56744. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  56745. i = repeatTimes - 1 - index;
  56746. }
  56747. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  56748. return {
  56749. position: position,
  56750. scale: symbolMeta.symbolScale.slice(),
  56751. rotation: symbolMeta.rotation
  56752. };
  56753. }
  56754. function onMouseOver() {
  56755. eachPath(bar, function (path) {
  56756. path.trigger('emphasis');
  56757. });
  56758. }
  56759. function onMouseOut() {
  56760. eachPath(bar, function (path) {
  56761. path.trigger('normal');
  56762. });
  56763. }
  56764. }
  56765. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  56766. var bundle = bar.__pictorialBundle;
  56767. var mainPath = bar.__pictorialMainPath;
  56768. if (!mainPath) {
  56769. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  56770. bundle.add(mainPath);
  56771. updateAttr(
  56772. mainPath,
  56773. {
  56774. position: symbolMeta.pathPosition.slice(),
  56775. scale: [0, 0],
  56776. rotation: symbolMeta.rotation
  56777. },
  56778. {
  56779. scale: symbolMeta.symbolScale.slice()
  56780. },
  56781. symbolMeta,
  56782. isUpdate
  56783. );
  56784. mainPath
  56785. .on('mouseover', onMouseOver)
  56786. .on('mouseout', onMouseOut);
  56787. }
  56788. else {
  56789. updateAttr(
  56790. mainPath,
  56791. null,
  56792. {
  56793. position: symbolMeta.pathPosition.slice(),
  56794. scale: symbolMeta.symbolScale.slice(),
  56795. rotation: symbolMeta.rotation
  56796. },
  56797. symbolMeta,
  56798. isUpdate
  56799. );
  56800. }
  56801. updateHoverAnimation(mainPath, symbolMeta);
  56802. function onMouseOver() {
  56803. this.trigger('emphasis');
  56804. }
  56805. function onMouseOut() {
  56806. this.trigger('normal');
  56807. }
  56808. }
  56809. // bar rect is used for label.
  56810. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  56811. var rectShape = extend({}, symbolMeta.barRectShape);
  56812. var barRect = bar.__pictorialBarRect;
  56813. if (!barRect) {
  56814. barRect = bar.__pictorialBarRect = new Rect({
  56815. z2: 2,
  56816. shape: rectShape,
  56817. silent: true,
  56818. style: {
  56819. stroke: 'transparent',
  56820. fill: 'transparent',
  56821. lineWidth: 0
  56822. }
  56823. });
  56824. bar.add(barRect);
  56825. }
  56826. else {
  56827. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  56828. }
  56829. }
  56830. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  56831. // If not clip, symbol will be remove and rebuilt.
  56832. if (symbolMeta.symbolClip) {
  56833. var clipPath = bar.__pictorialClipPath;
  56834. var clipShape = extend({}, symbolMeta.clipShape);
  56835. var valueDim = opt.valueDim;
  56836. var animationModel = symbolMeta.animationModel;
  56837. var dataIndex = symbolMeta.dataIndex;
  56838. if (clipPath) {
  56839. updateProps(
  56840. clipPath, {shape: clipShape}, animationModel, dataIndex
  56841. );
  56842. }
  56843. else {
  56844. clipShape[valueDim.wh] = 0;
  56845. clipPath = new Rect({shape: clipShape});
  56846. bar.__pictorialBundle.setClipPath(clipPath);
  56847. bar.__pictorialClipPath = clipPath;
  56848. var target = {};
  56849. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  56850. graphic[isUpdate ? 'updateProps' : 'initProps'](
  56851. clipPath, {shape: target}, animationModel, dataIndex
  56852. );
  56853. }
  56854. }
  56855. }
  56856. function getItemModel(data, dataIndex) {
  56857. var itemModel = data.getItemModel(dataIndex);
  56858. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  56859. itemModel.isAnimationEnabled = isAnimationEnabled;
  56860. return itemModel;
  56861. }
  56862. function getAnimationDelayParams(path) {
  56863. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  56864. return {
  56865. index: path.__pictorialAnimationIndex,
  56866. count: path.__pictorialRepeatTimes
  56867. };
  56868. }
  56869. function isAnimationEnabled() {
  56870. // `animation` prop can be set on itemModel in pictorial bar chart.
  56871. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  56872. }
  56873. function updateHoverAnimation(path, symbolMeta) {
  56874. path.off('emphasis').off('normal');
  56875. var scale = symbolMeta.symbolScale.slice();
  56876. symbolMeta.hoverAnimation && path
  56877. .on('emphasis', function () {
  56878. this.animateTo({
  56879. scale: [scale[0] * 1.1, scale[1] * 1.1]
  56880. }, 400, 'elasticOut');
  56881. })
  56882. .on('normal', function () {
  56883. this.animateTo({
  56884. scale: scale.slice()
  56885. }, 400, 'elasticOut');
  56886. });
  56887. }
  56888. function createBar(data, opt, symbolMeta, isUpdate) {
  56889. // bar is the main element for each data.
  56890. var bar = new Group();
  56891. // bundle is used for location and clip.
  56892. var bundle = new Group();
  56893. bar.add(bundle);
  56894. bar.__pictorialBundle = bundle;
  56895. bundle.attr('position', symbolMeta.bundlePosition.slice());
  56896. if (symbolMeta.symbolRepeat) {
  56897. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  56898. }
  56899. else {
  56900. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  56901. }
  56902. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  56903. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  56904. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  56905. bar.__pictorialSymbolMeta = symbolMeta;
  56906. return bar;
  56907. }
  56908. function updateBar(bar, opt, symbolMeta) {
  56909. var animationModel = symbolMeta.animationModel;
  56910. var dataIndex = symbolMeta.dataIndex;
  56911. var bundle = bar.__pictorialBundle;
  56912. updateProps(
  56913. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  56914. );
  56915. if (symbolMeta.symbolRepeat) {
  56916. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  56917. }
  56918. else {
  56919. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  56920. }
  56921. createOrUpdateBarRect(bar, symbolMeta, true);
  56922. createOrUpdateClip(bar, opt, symbolMeta, true);
  56923. }
  56924. function removeBar(data, dataIndex, animationModel, bar) {
  56925. // Not show text when animating
  56926. var labelRect = bar.__pictorialBarRect;
  56927. labelRect && (labelRect.style.text = null);
  56928. var pathes = [];
  56929. eachPath(bar, function (path) {
  56930. pathes.push(path);
  56931. });
  56932. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  56933. // I do not find proper remove animation for clip yet.
  56934. bar.__pictorialClipPath && (animationModel = null);
  56935. each$1(pathes, function (path) {
  56936. updateProps(
  56937. path, {scale: [0, 0]}, animationModel, dataIndex,
  56938. function () {
  56939. bar.parent && bar.parent.remove(bar);
  56940. }
  56941. );
  56942. });
  56943. data.setItemGraphicEl(dataIndex, null);
  56944. }
  56945. function getShapeStr(data, symbolMeta) {
  56946. return [
  56947. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  56948. !!symbolMeta.symbolRepeat,
  56949. !!symbolMeta.symbolClip
  56950. ].join(':');
  56951. }
  56952. function eachPath(bar, cb, context) {
  56953. // Do not use Group#eachChild, because it do not support remove.
  56954. each$1(bar.__pictorialBundle.children(), function (el) {
  56955. el !== bar.__pictorialBarRect && cb.call(context, el);
  56956. });
  56957. }
  56958. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  56959. immediateAttrs && el.attr(immediateAttrs);
  56960. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  56961. if (symbolMeta.symbolClip && !isUpdate) {
  56962. animationAttrs && el.attr(animationAttrs);
  56963. }
  56964. else {
  56965. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  56966. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  56967. );
  56968. }
  56969. }
  56970. function updateCommon$1(bar, opt, symbolMeta) {
  56971. var color = symbolMeta.color;
  56972. var dataIndex = symbolMeta.dataIndex;
  56973. var itemModel = symbolMeta.itemModel;
  56974. // Color must be excluded.
  56975. // Because symbol provide setColor individually to set fill and stroke
  56976. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  56977. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  56978. var cursorStyle = itemModel.getShallow('cursor');
  56979. eachPath(bar, function (path) {
  56980. // PENDING setColor should be before setStyle!!!
  56981. path.setColor(color);
  56982. path.setStyle(defaults(
  56983. {
  56984. fill: color,
  56985. opacity: symbolMeta.opacity
  56986. },
  56987. normalStyle
  56988. ));
  56989. setHoverStyle(path, hoverStyle);
  56990. cursorStyle && (path.cursor = cursorStyle);
  56991. path.z2 = symbolMeta.z2;
  56992. });
  56993. var barRectHoverStyle = {};
  56994. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  56995. var barRect = bar.__pictorialBarRect;
  56996. setLabel(
  56997. barRect.style, barRectHoverStyle, itemModel,
  56998. color, opt.seriesModel, dataIndex, barPositionOutside
  56999. );
  57000. setHoverStyle(barRect, barRectHoverStyle);
  57001. }
  57002. function toIntTimes(times) {
  57003. var roundedTimes = Math.round(times);
  57004. // Escapse accurate error
  57005. return Math.abs(times - roundedTimes) < 1e-4
  57006. ? roundedTimes
  57007. : Math.ceil(times);
  57008. }
  57009. /*
  57010. * Licensed to the Apache Software Foundation (ASF) under one
  57011. * or more contributor license agreements. See the NOTICE file
  57012. * distributed with this work for additional information
  57013. * regarding copyright ownership. The ASF licenses this file
  57014. * to you under the Apache License, Version 2.0 (the
  57015. * "License"); you may not use this file except in compliance
  57016. * with the License. You may obtain a copy of the License at
  57017. *
  57018. * http://www.apache.org/licenses/LICENSE-2.0
  57019. *
  57020. * Unless required by applicable law or agreed to in writing,
  57021. * software distributed under the License is distributed on an
  57022. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57023. * KIND, either express or implied. See the License for the
  57024. * specific language governing permissions and limitations
  57025. * under the License.
  57026. */
  57027. // In case developer forget to include grid component
  57028. registerLayout(curry(
  57029. layout, 'pictorialBar'
  57030. ));
  57031. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  57032. /*
  57033. * Licensed to the Apache Software Foundation (ASF) under one
  57034. * or more contributor license agreements. See the NOTICE file
  57035. * distributed with this work for additional information
  57036. * regarding copyright ownership. The ASF licenses this file
  57037. * to you under the Apache License, Version 2.0 (the
  57038. * "License"); you may not use this file except in compliance
  57039. * with the License. You may obtain a copy of the License at
  57040. *
  57041. * http://www.apache.org/licenses/LICENSE-2.0
  57042. *
  57043. * Unless required by applicable law or agreed to in writing,
  57044. * software distributed under the License is distributed on an
  57045. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57046. * KIND, either express or implied. See the License for the
  57047. * specific language governing permissions and limitations
  57048. * under the License.
  57049. */
  57050. /**
  57051. * @constructor module:echarts/coord/single/SingleAxis
  57052. * @extends {module:echarts/coord/Axis}
  57053. * @param {string} dim
  57054. * @param {*} scale
  57055. * @param {Array.<number>} coordExtent
  57056. * @param {string} axisType
  57057. * @param {string} position
  57058. */
  57059. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  57060. Axis.call(this, dim, scale, coordExtent);
  57061. /**
  57062. * Axis type
  57063. * - 'category'
  57064. * - 'value'
  57065. * - 'time'
  57066. * - 'log'
  57067. * @type {string}
  57068. */
  57069. this.type = axisType || 'value';
  57070. /**
  57071. * Axis position
  57072. * - 'top'
  57073. * - 'bottom'
  57074. * - 'left'
  57075. * - 'right'
  57076. * @type {string}
  57077. */
  57078. this.position = position || 'bottom';
  57079. /**
  57080. * Axis orient
  57081. * - 'horizontal'
  57082. * - 'vertical'
  57083. * @type {[type]}
  57084. */
  57085. this.orient = null;
  57086. };
  57087. SingleAxis.prototype = {
  57088. constructor: SingleAxis,
  57089. /**
  57090. * Axis model
  57091. * @type {module:echarts/coord/single/AxisModel}
  57092. */
  57093. model: null,
  57094. /**
  57095. * Judge the orient of the axis.
  57096. * @return {boolean}
  57097. */
  57098. isHorizontal: function () {
  57099. var position = this.position;
  57100. return position === 'top' || position === 'bottom';
  57101. },
  57102. /**
  57103. * @override
  57104. */
  57105. pointToData: function (point, clamp) {
  57106. return this.coordinateSystem.pointToData(point, clamp)[0];
  57107. },
  57108. /**
  57109. * Convert the local coord(processed by dataToCoord())
  57110. * to global coord(concrete pixel coord).
  57111. * designated by module:echarts/coord/single/Single.
  57112. * @type {Function}
  57113. */
  57114. toGlobalCoord: null,
  57115. /**
  57116. * Convert the global coord to local coord.
  57117. * designated by module:echarts/coord/single/Single.
  57118. * @type {Function}
  57119. */
  57120. toLocalCoord: null
  57121. };
  57122. inherits(SingleAxis, Axis);
  57123. /*
  57124. * Licensed to the Apache Software Foundation (ASF) under one
  57125. * or more contributor license agreements. See the NOTICE file
  57126. * distributed with this work for additional information
  57127. * regarding copyright ownership. The ASF licenses this file
  57128. * to you under the Apache License, Version 2.0 (the
  57129. * "License"); you may not use this file except in compliance
  57130. * with the License. You may obtain a copy of the License at
  57131. *
  57132. * http://www.apache.org/licenses/LICENSE-2.0
  57133. *
  57134. * Unless required by applicable law or agreed to in writing,
  57135. * software distributed under the License is distributed on an
  57136. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57137. * KIND, either express or implied. See the License for the
  57138. * specific language governing permissions and limitations
  57139. * under the License.
  57140. */
  57141. /**
  57142. * Single coordinates system.
  57143. */
  57144. /**
  57145. * Create a single coordinates system.
  57146. *
  57147. * @param {module:echarts/coord/single/AxisModel} axisModel
  57148. * @param {module:echarts/model/Global} ecModel
  57149. * @param {module:echarts/ExtensionAPI} api
  57150. */
  57151. function Single(axisModel, ecModel, api) {
  57152. /**
  57153. * @type {string}
  57154. * @readOnly
  57155. */
  57156. this.dimension = 'single';
  57157. /**
  57158. * Add it just for draw tooltip.
  57159. *
  57160. * @type {Array.<string>}
  57161. * @readOnly
  57162. */
  57163. this.dimensions = ['single'];
  57164. /**
  57165. * @private
  57166. * @type {module:echarts/coord/single/SingleAxis}.
  57167. */
  57168. this._axis = null;
  57169. /**
  57170. * @private
  57171. * @type {module:zrender/core/BoundingRect}
  57172. */
  57173. this._rect;
  57174. this._init(axisModel, ecModel, api);
  57175. /**
  57176. * @type {module:echarts/coord/single/AxisModel}
  57177. */
  57178. this.model = axisModel;
  57179. }
  57180. Single.prototype = {
  57181. type: 'singleAxis',
  57182. axisPointerEnabled: true,
  57183. constructor: Single,
  57184. /**
  57185. * Initialize single coordinate system.
  57186. *
  57187. * @param {module:echarts/coord/single/AxisModel} axisModel
  57188. * @param {module:echarts/model/Global} ecModel
  57189. * @param {module:echarts/ExtensionAPI} api
  57190. * @private
  57191. */
  57192. _init: function (axisModel, ecModel, api) {
  57193. var dim = this.dimension;
  57194. var axis = new SingleAxis(
  57195. dim,
  57196. createScaleByModel(axisModel),
  57197. [0, 0],
  57198. axisModel.get('type'),
  57199. axisModel.get('position')
  57200. );
  57201. var isCategory = axis.type === 'category';
  57202. axis.onBand = isCategory && axisModel.get('boundaryGap');
  57203. axis.inverse = axisModel.get('inverse');
  57204. axis.orient = axisModel.get('orient');
  57205. axisModel.axis = axis;
  57206. axis.model = axisModel;
  57207. axis.coordinateSystem = this;
  57208. this._axis = axis;
  57209. },
  57210. /**
  57211. * Update axis scale after data processed
  57212. * @param {module:echarts/model/Global} ecModel
  57213. * @param {module:echarts/ExtensionAPI} api
  57214. */
  57215. update: function (ecModel, api) {
  57216. ecModel.eachSeries(function (seriesModel) {
  57217. if (seriesModel.coordinateSystem === this) {
  57218. var data = seriesModel.getData();
  57219. each$1(data.mapDimension(this.dimension, true), function (dim) {
  57220. this._axis.scale.unionExtentFromData(data, dim);
  57221. }, this);
  57222. niceScaleExtent(this._axis.scale, this._axis.model);
  57223. }
  57224. }, this);
  57225. },
  57226. /**
  57227. * Resize the single coordinate system.
  57228. *
  57229. * @param {module:echarts/coord/single/AxisModel} axisModel
  57230. * @param {module:echarts/ExtensionAPI} api
  57231. */
  57232. resize: function (axisModel, api) {
  57233. this._rect = getLayoutRect(
  57234. {
  57235. left: axisModel.get('left'),
  57236. top: axisModel.get('top'),
  57237. right: axisModel.get('right'),
  57238. bottom: axisModel.get('bottom'),
  57239. width: axisModel.get('width'),
  57240. height: axisModel.get('height')
  57241. },
  57242. {
  57243. width: api.getWidth(),
  57244. height: api.getHeight()
  57245. }
  57246. );
  57247. this._adjustAxis();
  57248. },
  57249. /**
  57250. * @return {module:zrender/core/BoundingRect}
  57251. */
  57252. getRect: function () {
  57253. return this._rect;
  57254. },
  57255. /**
  57256. * @private
  57257. */
  57258. _adjustAxis: function () {
  57259. var rect = this._rect;
  57260. var axis = this._axis;
  57261. var isHorizontal = axis.isHorizontal();
  57262. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  57263. var idx = axis.reverse ? 1 : 0;
  57264. axis.setExtent(extent[idx], extent[1 - idx]);
  57265. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  57266. },
  57267. /**
  57268. * @param {module:echarts/coord/single/SingleAxis} axis
  57269. * @param {number} coordBase
  57270. */
  57271. _updateAxisTransform: function (axis, coordBase) {
  57272. var axisExtent = axis.getExtent();
  57273. var extentSum = axisExtent[0] + axisExtent[1];
  57274. var isHorizontal = axis.isHorizontal();
  57275. axis.toGlobalCoord = isHorizontal
  57276. ? function (coord) {
  57277. return coord + coordBase;
  57278. }
  57279. : function (coord) {
  57280. return extentSum - coord + coordBase;
  57281. };
  57282. axis.toLocalCoord = isHorizontal
  57283. ? function (coord) {
  57284. return coord - coordBase;
  57285. }
  57286. : function (coord) {
  57287. return extentSum - coord + coordBase;
  57288. };
  57289. },
  57290. /**
  57291. * Get axis.
  57292. *
  57293. * @return {module:echarts/coord/single/SingleAxis}
  57294. */
  57295. getAxis: function () {
  57296. return this._axis;
  57297. },
  57298. /**
  57299. * Get axis, add it just for draw tooltip.
  57300. *
  57301. * @return {[type]} [description]
  57302. */
  57303. getBaseAxis: function () {
  57304. return this._axis;
  57305. },
  57306. /**
  57307. * @return {Array.<module:echarts/coord/Axis>}
  57308. */
  57309. getAxes: function () {
  57310. return [this._axis];
  57311. },
  57312. /**
  57313. * @return {Object} {baseAxes: [], otherAxes: []}
  57314. */
  57315. getTooltipAxes: function () {
  57316. return {baseAxes: [this.getAxis()]};
  57317. },
  57318. /**
  57319. * If contain point.
  57320. *
  57321. * @param {Array.<number>} point
  57322. * @return {boolean}
  57323. */
  57324. containPoint: function (point) {
  57325. var rect = this.getRect();
  57326. var axis = this.getAxis();
  57327. var orient = axis.orient;
  57328. if (orient === 'horizontal') {
  57329. return axis.contain(axis.toLocalCoord(point[0]))
  57330. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  57331. }
  57332. else {
  57333. return axis.contain(axis.toLocalCoord(point[1]))
  57334. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  57335. }
  57336. },
  57337. /**
  57338. * @param {Array.<number>} point
  57339. * @return {Array.<number>}
  57340. */
  57341. pointToData: function (point) {
  57342. var axis = this.getAxis();
  57343. return [axis.coordToData(axis.toLocalCoord(
  57344. point[axis.orient === 'horizontal' ? 0 : 1]
  57345. ))];
  57346. },
  57347. /**
  57348. * Convert the series data to concrete point.
  57349. *
  57350. * @param {number|Array.<number>} val
  57351. * @return {Array.<number>}
  57352. */
  57353. dataToPoint: function (val) {
  57354. var axis = this.getAxis();
  57355. var rect = this.getRect();
  57356. var pt = [];
  57357. var idx = axis.orient === 'horizontal' ? 0 : 1;
  57358. if (val instanceof Array) {
  57359. val = val[0];
  57360. }
  57361. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  57362. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  57363. return pt;
  57364. }
  57365. };
  57366. /*
  57367. * Licensed to the Apache Software Foundation (ASF) under one
  57368. * or more contributor license agreements. See the NOTICE file
  57369. * distributed with this work for additional information
  57370. * regarding copyright ownership. The ASF licenses this file
  57371. * to you under the Apache License, Version 2.0 (the
  57372. * "License"); you may not use this file except in compliance
  57373. * with the License. You may obtain a copy of the License at
  57374. *
  57375. * http://www.apache.org/licenses/LICENSE-2.0
  57376. *
  57377. * Unless required by applicable law or agreed to in writing,
  57378. * software distributed under the License is distributed on an
  57379. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57380. * KIND, either express or implied. See the License for the
  57381. * specific language governing permissions and limitations
  57382. * under the License.
  57383. */
  57384. /**
  57385. * Single coordinate system creator.
  57386. */
  57387. /**
  57388. * Create single coordinate system and inject it into seriesModel.
  57389. *
  57390. * @param {module:echarts/model/Global} ecModel
  57391. * @param {module:echarts/ExtensionAPI} api
  57392. * @return {Array.<module:echarts/coord/single/Single>}
  57393. */
  57394. function create$3(ecModel, api) {
  57395. var singles = [];
  57396. ecModel.eachComponent('singleAxis', function (axisModel, idx) {
  57397. var single = new Single(axisModel, ecModel, api);
  57398. single.name = 'single_' + idx;
  57399. single.resize(axisModel, api);
  57400. axisModel.coordinateSystem = single;
  57401. singles.push(single);
  57402. });
  57403. ecModel.eachSeries(function (seriesModel) {
  57404. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  57405. var singleAxisModel = ecModel.queryComponents({
  57406. mainType: 'singleAxis',
  57407. index: seriesModel.get('singleAxisIndex'),
  57408. id: seriesModel.get('singleAxisId')
  57409. })[0];
  57410. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  57411. }
  57412. });
  57413. return singles;
  57414. }
  57415. CoordinateSystemManager.register('single', {
  57416. create: create$3,
  57417. dimensions: Single.prototype.dimensions
  57418. });
  57419. /*
  57420. * Licensed to the Apache Software Foundation (ASF) under one
  57421. * or more contributor license agreements. See the NOTICE file
  57422. * distributed with this work for additional information
  57423. * regarding copyright ownership. The ASF licenses this file
  57424. * to you under the Apache License, Version 2.0 (the
  57425. * "License"); you may not use this file except in compliance
  57426. * with the License. You may obtain a copy of the License at
  57427. *
  57428. * http://www.apache.org/licenses/LICENSE-2.0
  57429. *
  57430. * Unless required by applicable law or agreed to in writing,
  57431. * software distributed under the License is distributed on an
  57432. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57433. * KIND, either express or implied. See the License for the
  57434. * specific language governing permissions and limitations
  57435. * under the License.
  57436. */
  57437. /**
  57438. * @param {Object} opt {labelInside}
  57439. * @return {Object} {
  57440. * position, rotation, labelDirection, labelOffset,
  57441. * tickDirection, labelRotate, z2
  57442. * }
  57443. */
  57444. function layout$2(axisModel, opt) {
  57445. opt = opt || {};
  57446. var single = axisModel.coordinateSystem;
  57447. var axis = axisModel.axis;
  57448. var layout = {};
  57449. var axisPosition = axis.position;
  57450. var orient = axis.orient;
  57451. var rect = single.getRect();
  57452. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  57453. var positionMap = {
  57454. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  57455. vertical: {left: rectBound[0], right: rectBound[1]}
  57456. };
  57457. layout.position = [
  57458. orient === 'vertical'
  57459. ? positionMap.vertical[axisPosition]
  57460. : rectBound[0],
  57461. orient === 'horizontal'
  57462. ? positionMap.horizontal[axisPosition]
  57463. : rectBound[3]
  57464. ];
  57465. var r = {horizontal: 0, vertical: 1};
  57466. layout.rotation = Math.PI / 2 * r[orient];
  57467. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  57468. layout.labelDirection = layout.tickDirection
  57469. = layout.nameDirection
  57470. = directionMap[axisPosition];
  57471. if (axisModel.get('axisTick.inside')) {
  57472. layout.tickDirection = -layout.tickDirection;
  57473. }
  57474. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  57475. layout.labelDirection = -layout.labelDirection;
  57476. }
  57477. var labelRotation = opt.rotate;
  57478. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  57479. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  57480. layout.z2 = 1;
  57481. return layout;
  57482. }
  57483. /*
  57484. * Licensed to the Apache Software Foundation (ASF) under one
  57485. * or more contributor license agreements. See the NOTICE file
  57486. * distributed with this work for additional information
  57487. * regarding copyright ownership. The ASF licenses this file
  57488. * to you under the Apache License, Version 2.0 (the
  57489. * "License"); you may not use this file except in compliance
  57490. * with the License. You may obtain a copy of the License at
  57491. *
  57492. * http://www.apache.org/licenses/LICENSE-2.0
  57493. *
  57494. * Unless required by applicable law or agreed to in writing,
  57495. * software distributed under the License is distributed on an
  57496. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57497. * KIND, either express or implied. See the License for the
  57498. * specific language governing permissions and limitations
  57499. * under the License.
  57500. */
  57501. var axisBuilderAttrs$2 = [
  57502. 'axisLine', 'axisTickLabel', 'axisName'
  57503. ];
  57504. var selfBuilderAttr = 'splitLine';
  57505. var SingleAxisView = AxisView.extend({
  57506. type: 'singleAxis',
  57507. axisPointerClass: 'SingleAxisPointer',
  57508. render: function (axisModel, ecModel, api, payload) {
  57509. var group = this.group;
  57510. group.removeAll();
  57511. var layout = layout$2(axisModel);
  57512. var axisBuilder = new AxisBuilder(axisModel, layout);
  57513. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  57514. group.add(axisBuilder.getGroup());
  57515. if (axisModel.get(selfBuilderAttr + '.show')) {
  57516. this['_' + selfBuilderAttr](axisModel);
  57517. }
  57518. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  57519. },
  57520. _splitLine: function (axisModel) {
  57521. var axis = axisModel.axis;
  57522. if (axis.scale.isBlank()) {
  57523. return;
  57524. }
  57525. var splitLineModel = axisModel.getModel('splitLine');
  57526. var lineStyleModel = splitLineModel.getModel('lineStyle');
  57527. var lineWidth = lineStyleModel.get('width');
  57528. var lineColors = lineStyleModel.get('color');
  57529. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  57530. var gridRect = axisModel.coordinateSystem.getRect();
  57531. var isHorizontal = axis.isHorizontal();
  57532. var splitLines = [];
  57533. var lineCount = 0;
  57534. var ticksCoords = axis.getTicksCoords({
  57535. tickModel: splitLineModel
  57536. });
  57537. var p1 = [];
  57538. var p2 = [];
  57539. for (var i = 0; i < ticksCoords.length; ++i) {
  57540. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  57541. if (isHorizontal) {
  57542. p1[0] = tickCoord;
  57543. p1[1] = gridRect.y;
  57544. p2[0] = tickCoord;
  57545. p2[1] = gridRect.y + gridRect.height;
  57546. }
  57547. else {
  57548. p1[0] = gridRect.x;
  57549. p1[1] = tickCoord;
  57550. p2[0] = gridRect.x + gridRect.width;
  57551. p2[1] = tickCoord;
  57552. }
  57553. var colorIndex = (lineCount++) % lineColors.length;
  57554. splitLines[colorIndex] = splitLines[colorIndex] || [];
  57555. splitLines[colorIndex].push(new Line(
  57556. subPixelOptimizeLine({
  57557. shape: {
  57558. x1: p1[0],
  57559. y1: p1[1],
  57560. x2: p2[0],
  57561. y2: p2[1]
  57562. },
  57563. style: {
  57564. lineWidth: lineWidth
  57565. },
  57566. silent: true
  57567. })));
  57568. }
  57569. for (var i = 0; i < splitLines.length; ++i) {
  57570. this.group.add(mergePath(splitLines[i], {
  57571. style: {
  57572. stroke: lineColors[i % lineColors.length],
  57573. lineDash: lineStyleModel.getLineDash(lineWidth),
  57574. lineWidth: lineWidth
  57575. },
  57576. silent: true
  57577. }));
  57578. }
  57579. }
  57580. });
  57581. /*
  57582. * Licensed to the Apache Software Foundation (ASF) under one
  57583. * or more contributor license agreements. See the NOTICE file
  57584. * distributed with this work for additional information
  57585. * regarding copyright ownership. The ASF licenses this file
  57586. * to you under the Apache License, Version 2.0 (the
  57587. * "License"); you may not use this file except in compliance
  57588. * with the License. You may obtain a copy of the License at
  57589. *
  57590. * http://www.apache.org/licenses/LICENSE-2.0
  57591. *
  57592. * Unless required by applicable law or agreed to in writing,
  57593. * software distributed under the License is distributed on an
  57594. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57595. * KIND, either express or implied. See the License for the
  57596. * specific language governing permissions and limitations
  57597. * under the License.
  57598. */
  57599. var AxisModel$4 = ComponentModel.extend({
  57600. type: 'singleAxis',
  57601. layoutMode: 'box',
  57602. /**
  57603. * @type {module:echarts/coord/single/SingleAxis}
  57604. */
  57605. axis: null,
  57606. /**
  57607. * @type {module:echarts/coord/single/Single}
  57608. */
  57609. coordinateSystem: null,
  57610. /**
  57611. * @override
  57612. */
  57613. getCoordSysModel: function () {
  57614. return this;
  57615. }
  57616. });
  57617. var defaultOption$2 = {
  57618. left: '5%',
  57619. top: '5%',
  57620. right: '5%',
  57621. bottom: '5%',
  57622. type: 'value',
  57623. position: 'bottom',
  57624. orient: 'horizontal',
  57625. axisLine: {
  57626. show: true,
  57627. lineStyle: {
  57628. width: 2,
  57629. type: 'solid'
  57630. }
  57631. },
  57632. // Single coordinate system and single axis is the,
  57633. // which is used as the parent tooltip model.
  57634. // same model, so we set default tooltip show as true.
  57635. tooltip: {
  57636. show: true
  57637. },
  57638. axisTick: {
  57639. show: true,
  57640. length: 6,
  57641. lineStyle: {
  57642. width: 2
  57643. }
  57644. },
  57645. axisLabel: {
  57646. show: true,
  57647. interval: 'auto'
  57648. },
  57649. splitLine: {
  57650. show: true,
  57651. lineStyle: {
  57652. type: 'dashed',
  57653. opacity: 0.2
  57654. }
  57655. }
  57656. };
  57657. function getAxisType$2(axisName, option) {
  57658. return option.type || (option.data ? 'category' : 'value');
  57659. }
  57660. merge(AxisModel$4.prototype, axisModelCommonMixin);
  57661. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  57662. /*
  57663. * Licensed to the Apache Software Foundation (ASF) under one
  57664. * or more contributor license agreements. See the NOTICE file
  57665. * distributed with this work for additional information
  57666. * regarding copyright ownership. The ASF licenses this file
  57667. * to you under the Apache License, Version 2.0 (the
  57668. * "License"); you may not use this file except in compliance
  57669. * with the License. You may obtain a copy of the License at
  57670. *
  57671. * http://www.apache.org/licenses/LICENSE-2.0
  57672. *
  57673. * Unless required by applicable law or agreed to in writing,
  57674. * software distributed under the License is distributed on an
  57675. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57676. * KIND, either express or implied. See the License for the
  57677. * specific language governing permissions and limitations
  57678. * under the License.
  57679. */
  57680. /**
  57681. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  57682. * @param {module:echarts/model/Global} ecModel
  57683. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  57684. */
  57685. var findPointFromSeries = function (finder, ecModel) {
  57686. var point = [];
  57687. var seriesIndex = finder.seriesIndex;
  57688. var seriesModel;
  57689. if (seriesIndex == null || !(
  57690. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  57691. )) {
  57692. return {point: []};
  57693. }
  57694. var data = seriesModel.getData();
  57695. var dataIndex = queryDataIndex(data, finder);
  57696. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  57697. return {point: []};
  57698. }
  57699. var el = data.getItemGraphicEl(dataIndex);
  57700. var coordSys = seriesModel.coordinateSystem;
  57701. if (seriesModel.getTooltipPosition) {
  57702. point = seriesModel.getTooltipPosition(dataIndex) || [];
  57703. }
  57704. else if (coordSys && coordSys.dataToPoint) {
  57705. point = coordSys.dataToPoint(
  57706. data.getValues(
  57707. map(coordSys.dimensions, function (dim) {
  57708. return data.mapDimension(dim);
  57709. }), dataIndex, true
  57710. )
  57711. ) || [];
  57712. }
  57713. else if (el) {
  57714. // Use graphic bounding rect
  57715. var rect = el.getBoundingRect().clone();
  57716. rect.applyTransform(el.transform);
  57717. point = [
  57718. rect.x + rect.width / 2,
  57719. rect.y + rect.height / 2
  57720. ];
  57721. }
  57722. return {point: point, el: el};
  57723. };
  57724. /*
  57725. * Licensed to the Apache Software Foundation (ASF) under one
  57726. * or more contributor license agreements. See the NOTICE file
  57727. * distributed with this work for additional information
  57728. * regarding copyright ownership. The ASF licenses this file
  57729. * to you under the Apache License, Version 2.0 (the
  57730. * "License"); you may not use this file except in compliance
  57731. * with the License. You may obtain a copy of the License at
  57732. *
  57733. * http://www.apache.org/licenses/LICENSE-2.0
  57734. *
  57735. * Unless required by applicable law or agreed to in writing,
  57736. * software distributed under the License is distributed on an
  57737. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57738. * KIND, either express or implied. See the License for the
  57739. * specific language governing permissions and limitations
  57740. * under the License.
  57741. */
  57742. var each$14 = each$1;
  57743. var curry$3 = curry;
  57744. var inner$9 = makeInner();
  57745. /**
  57746. * Basic logic: check all axis, if they do not demand show/highlight,
  57747. * then hide/downplay them.
  57748. *
  57749. * @param {Object} coordSysAxesInfo
  57750. * @param {Object} payload
  57751. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  57752. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  57753. * trigger axisPointer and tooltip.
  57754. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  57755. * trigger axisPointer and tooltip.
  57756. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  57757. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  57758. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  57759. * [{
  57760. * axisDim: 'x'|'y'|'angle'|...,
  57761. * axisIndex: ...,
  57762. * value: ...
  57763. * }, ...]
  57764. * @param {Function} [payload.dispatchAction]
  57765. * @param {Object} [payload.tooltipOption]
  57766. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  57767. * which can be specified in dispatchAction
  57768. * @param {module:echarts/model/Global} ecModel
  57769. * @param {module:echarts/ExtensionAPI} api
  57770. * @return {Object} content of event obj for echarts.connect.
  57771. */
  57772. var axisTrigger = function (payload, ecModel, api) {
  57773. var currTrigger = payload.currTrigger;
  57774. var point = [payload.x, payload.y];
  57775. var finder = payload;
  57776. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  57777. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  57778. // Pending
  57779. // See #6121. But we are not able to reproduce it yet.
  57780. if (!coordSysAxesInfo) {
  57781. return;
  57782. }
  57783. if (illegalPoint(point)) {
  57784. // Used in the default behavior of `connection`: use the sample seriesIndex
  57785. // and dataIndex. And also used in the tooltipView trigger.
  57786. point = findPointFromSeries({
  57787. seriesIndex: finder.seriesIndex,
  57788. // Do not use dataIndexInside from other ec instance.
  57789. // FIXME: auto detect it?
  57790. dataIndex: finder.dataIndex
  57791. }, ecModel).point;
  57792. }
  57793. var isIllegalPoint = illegalPoint(point);
  57794. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  57795. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  57796. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  57797. // and dataIndex.
  57798. var inputAxesInfo = finder.axesInfo;
  57799. var axesInfo = coordSysAxesInfo.axesInfo;
  57800. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  57801. var outputFinder = {};
  57802. var showValueMap = {};
  57803. var dataByCoordSys = {list: [], map: {}};
  57804. var updaters = {
  57805. showPointer: curry$3(showPointer, showValueMap),
  57806. showTooltip: curry$3(showTooltip, dataByCoordSys)
  57807. };
  57808. // Process for triggered axes.
  57809. each$14(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  57810. // If a point given, it must be contained by the coordinate system.
  57811. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  57812. each$14(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  57813. var axis = axisInfo.axis;
  57814. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  57815. // If no inputAxesInfo, no axis is restricted.
  57816. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  57817. var val = inputAxisInfo && inputAxisInfo.value;
  57818. if (val == null && !isIllegalPoint) {
  57819. val = axis.pointToData(point);
  57820. }
  57821. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  57822. }
  57823. });
  57824. });
  57825. // Process for linked axes.
  57826. var linkTriggers = {};
  57827. each$14(axesInfo, function (tarAxisInfo, tarKey) {
  57828. var linkGroup = tarAxisInfo.linkGroup;
  57829. // If axis has been triggered in the previous stage, it should not be triggered by link.
  57830. if (linkGroup && !showValueMap[tarKey]) {
  57831. each$14(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  57832. var srcValItem = showValueMap[srcKey];
  57833. // If srcValItem exist, source axis is triggered, so link to target axis.
  57834. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  57835. var val = srcValItem.value;
  57836. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  57837. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  57838. )));
  57839. linkTriggers[tarAxisInfo.key] = val;
  57840. }
  57841. });
  57842. }
  57843. });
  57844. each$14(linkTriggers, function (val, tarKey) {
  57845. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  57846. });
  57847. updateModelActually(showValueMap, axesInfo, outputFinder);
  57848. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  57849. dispatchHighDownActually(axesInfo, dispatchAction, api);
  57850. return outputFinder;
  57851. };
  57852. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  57853. var axis = axisInfo.axis;
  57854. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  57855. return;
  57856. }
  57857. if (!axisInfo.involveSeries) {
  57858. updaters.showPointer(axisInfo, newValue);
  57859. return;
  57860. }
  57861. // Heavy calculation. So put it after axis.containData checking.
  57862. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  57863. var payloadBatch = payloadInfo.payloadBatch;
  57864. var snapToValue = payloadInfo.snapToValue;
  57865. // Fill content of event obj for echarts.connect.
  57866. // By defualt use the first involved series data as a sample to connect.
  57867. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  57868. extend(outputFinder, payloadBatch[0]);
  57869. }
  57870. // If no linkSource input, this process is for collecting link
  57871. // target, where snap should not be accepted.
  57872. if (!dontSnap && axisInfo.snap) {
  57873. if (axis.containData(snapToValue) && snapToValue != null) {
  57874. newValue = snapToValue;
  57875. }
  57876. }
  57877. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  57878. // Tooltip should always be snapToValue, otherwise there will be
  57879. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  57880. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  57881. }
  57882. function buildPayloadsBySeries(value, axisInfo) {
  57883. var axis = axisInfo.axis;
  57884. var dim = axis.dim;
  57885. var snapToValue = value;
  57886. var payloadBatch = [];
  57887. var minDist = Number.MAX_VALUE;
  57888. var minDiff = -1;
  57889. each$14(axisInfo.seriesModels, function (series, idx) {
  57890. var dataDim = series.getData().mapDimension(dim, true);
  57891. var seriesNestestValue;
  57892. var dataIndices;
  57893. if (series.getAxisTooltipData) {
  57894. var result = series.getAxisTooltipData(dataDim, value, axis);
  57895. dataIndices = result.dataIndices;
  57896. seriesNestestValue = result.nestestValue;
  57897. }
  57898. else {
  57899. dataIndices = series.getData().indicesOfNearest(
  57900. dataDim[0],
  57901. value,
  57902. // Add a threshold to avoid find the wrong dataIndex
  57903. // when data length is not same.
  57904. // false,
  57905. axis.type === 'category' ? 0.5 : null
  57906. );
  57907. if (!dataIndices.length) {
  57908. return;
  57909. }
  57910. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  57911. }
  57912. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  57913. return;
  57914. }
  57915. var diff = value - seriesNestestValue;
  57916. var dist = Math.abs(diff);
  57917. // Consider category case
  57918. if (dist <= minDist) {
  57919. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  57920. minDist = dist;
  57921. minDiff = diff;
  57922. snapToValue = seriesNestestValue;
  57923. payloadBatch.length = 0;
  57924. }
  57925. each$14(dataIndices, function (dataIndex) {
  57926. payloadBatch.push({
  57927. seriesIndex: series.seriesIndex,
  57928. dataIndexInside: dataIndex,
  57929. dataIndex: series.getData().getRawIndex(dataIndex)
  57930. });
  57931. });
  57932. }
  57933. });
  57934. return {
  57935. payloadBatch: payloadBatch,
  57936. snapToValue: snapToValue
  57937. };
  57938. }
  57939. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  57940. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  57941. }
  57942. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  57943. var payloadBatch = payloadInfo.payloadBatch;
  57944. var axis = axisInfo.axis;
  57945. var axisModel = axis.model;
  57946. var axisPointerModel = axisInfo.axisPointerModel;
  57947. // If no data, do not create anything in dataByCoordSys,
  57948. // whose length will be used to judge whether dispatch action.
  57949. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  57950. return;
  57951. }
  57952. var coordSysModel = axisInfo.coordSys.model;
  57953. var coordSysKey = makeKey(coordSysModel);
  57954. var coordSysItem = dataByCoordSys.map[coordSysKey];
  57955. if (!coordSysItem) {
  57956. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  57957. coordSysId: coordSysModel.id,
  57958. coordSysIndex: coordSysModel.componentIndex,
  57959. coordSysType: coordSysModel.type,
  57960. coordSysMainType: coordSysModel.mainType,
  57961. dataByAxis: []
  57962. };
  57963. dataByCoordSys.list.push(coordSysItem);
  57964. }
  57965. coordSysItem.dataByAxis.push({
  57966. axisDim: axis.dim,
  57967. axisIndex: axisModel.componentIndex,
  57968. axisType: axisModel.type,
  57969. axisId: axisModel.id,
  57970. value: value,
  57971. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  57972. // depends that all models have been updated. So it should not be performed
  57973. // here. Considering axisPointerModel used here is volatile, which is hard
  57974. // to be retrieve in TooltipView, we prepare parameters here.
  57975. valueLabelOpt: {
  57976. precision: axisPointerModel.get('label.precision'),
  57977. formatter: axisPointerModel.get('label.formatter')
  57978. },
  57979. seriesDataIndices: payloadBatch.slice()
  57980. });
  57981. }
  57982. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  57983. var outputAxesInfo = outputFinder.axesInfo = [];
  57984. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  57985. each$14(axesInfo, function (axisInfo, key) {
  57986. var option = axisInfo.axisPointerModel.option;
  57987. var valItem = showValueMap[key];
  57988. if (valItem) {
  57989. !axisInfo.useHandle && (option.status = 'show');
  57990. option.value = valItem.value;
  57991. // For label formatter param and highlight.
  57992. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  57993. }
  57994. // When always show (e.g., handle used), remain
  57995. // original value and status.
  57996. else {
  57997. // If hide, value still need to be set, consider
  57998. // click legend to toggle axis blank.
  57999. !axisInfo.useHandle && (option.status = 'hide');
  58000. }
  58001. // If status is 'hide', should be no info in payload.
  58002. option.status === 'show' && outputAxesInfo.push({
  58003. axisDim: axisInfo.axis.dim,
  58004. axisIndex: axisInfo.axis.model.componentIndex,
  58005. value: option.value
  58006. });
  58007. });
  58008. }
  58009. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  58010. // Basic logic: If no showTip required, hideTip will be dispatched.
  58011. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  58012. dispatchAction({type: 'hideTip'});
  58013. return;
  58014. }
  58015. // In most case only one axis (or event one series is used). It is
  58016. // convinient to fetch payload.seriesIndex and payload.dataIndex
  58017. // dirtectly. So put the first seriesIndex and dataIndex of the first
  58018. // axis on the payload.
  58019. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  58020. dispatchAction({
  58021. type: 'showTip',
  58022. escapeConnect: true,
  58023. x: point[0],
  58024. y: point[1],
  58025. tooltipOption: payload.tooltipOption,
  58026. position: payload.position,
  58027. dataIndexInside: sampleItem.dataIndexInside,
  58028. dataIndex: sampleItem.dataIndex,
  58029. seriesIndex: sampleItem.seriesIndex,
  58030. dataByCoordSys: dataByCoordSys.list
  58031. });
  58032. }
  58033. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  58034. // FIXME
  58035. // highlight status modification shoule be a stage of main process?
  58036. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  58037. var zr = api.getZr();
  58038. var highDownKey = 'axisPointerLastHighlights';
  58039. var lastHighlights = inner$9(zr)[highDownKey] || {};
  58040. var newHighlights = inner$9(zr)[highDownKey] = {};
  58041. // Update highlight/downplay status according to axisPointer model.
  58042. // Build hash map and remove duplicate incidentally.
  58043. each$14(axesInfo, function (axisInfo, key) {
  58044. var option = axisInfo.axisPointerModel.option;
  58045. option.status === 'show' && each$14(option.seriesDataIndices, function (batchItem) {
  58046. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  58047. newHighlights[key] = batchItem;
  58048. });
  58049. });
  58050. // Diff.
  58051. var toHighlight = [];
  58052. var toDownplay = [];
  58053. each$1(lastHighlights, function (batchItem, key) {
  58054. !newHighlights[key] && toDownplay.push(batchItem);
  58055. });
  58056. each$1(newHighlights, function (batchItem, key) {
  58057. !lastHighlights[key] && toHighlight.push(batchItem);
  58058. });
  58059. toDownplay.length && api.dispatchAction({
  58060. type: 'downplay', escapeConnect: true, batch: toDownplay
  58061. });
  58062. toHighlight.length && api.dispatchAction({
  58063. type: 'highlight', escapeConnect: true, batch: toHighlight
  58064. });
  58065. }
  58066. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  58067. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  58068. var inputAxisInfo = inputAxesInfo[i];
  58069. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  58070. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  58071. ) {
  58072. return inputAxisInfo;
  58073. }
  58074. }
  58075. }
  58076. function makeMapperParam(axisInfo) {
  58077. var axisModel = axisInfo.axis.model;
  58078. var item = {};
  58079. var dim = item.axisDim = axisInfo.axis.dim;
  58080. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  58081. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  58082. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  58083. return item;
  58084. }
  58085. function illegalPoint(point) {
  58086. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  58087. }
  58088. /*
  58089. * Licensed to the Apache Software Foundation (ASF) under one
  58090. * or more contributor license agreements. See the NOTICE file
  58091. * distributed with this work for additional information
  58092. * regarding copyright ownership. The ASF licenses this file
  58093. * to you under the Apache License, Version 2.0 (the
  58094. * "License"); you may not use this file except in compliance
  58095. * with the License. You may obtain a copy of the License at
  58096. *
  58097. * http://www.apache.org/licenses/LICENSE-2.0
  58098. *
  58099. * Unless required by applicable law or agreed to in writing,
  58100. * software distributed under the License is distributed on an
  58101. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58102. * KIND, either express or implied. See the License for the
  58103. * specific language governing permissions and limitations
  58104. * under the License.
  58105. */
  58106. var AxisPointerModel = extendComponentModel({
  58107. type: 'axisPointer',
  58108. coordSysAxesInfo: null,
  58109. defaultOption: {
  58110. // 'auto' means that show when triggered by tooltip or handle.
  58111. show: 'auto',
  58112. // 'click' | 'mousemove' | 'none'
  58113. triggerOn: null, // set default in AxisPonterView.js
  58114. zlevel: 0,
  58115. z: 50,
  58116. type: 'line', // 'line' 'shadow' 'cross' 'none'.
  58117. // axispointer triggered by tootip determine snap automatically,
  58118. // see `modelHelper`.
  58119. snap: false,
  58120. triggerTooltip: true,
  58121. value: null,
  58122. status: null, // Init value depends on whether handle is used.
  58123. // [group0, group1, ...]
  58124. // Each group can be: {
  58125. // mapper: function () {},
  58126. // singleTooltip: 'multiple', // 'multiple' or 'single'
  58127. // xAxisId: ...,
  58128. // yAxisName: ...,
  58129. // angleAxisIndex: ...
  58130. // }
  58131. // mapper: can be ignored.
  58132. // input: {axisInfo, value}
  58133. // output: {axisInfo, value}
  58134. link: [],
  58135. // Do not set 'auto' here, otherwise global animation: false
  58136. // will not effect at this axispointer.
  58137. animation: null,
  58138. animationDurationUpdate: 200,
  58139. lineStyle: {
  58140. color: '#aaa',
  58141. width: 1,
  58142. type: 'solid'
  58143. },
  58144. shadowStyle: {
  58145. color: 'rgba(150,150,150,0.3)'
  58146. },
  58147. label: {
  58148. show: true,
  58149. formatter: null, // string | Function
  58150. precision: 'auto', // Or a number like 0, 1, 2 ...
  58151. margin: 3,
  58152. color: '#fff',
  58153. padding: [5, 7, 5, 7],
  58154. backgroundColor: 'auto', // default: axis line color
  58155. borderColor: null,
  58156. borderWidth: 0,
  58157. shadowBlur: 3,
  58158. shadowColor: '#aaa'
  58159. // Considering applicability, common style should
  58160. // better not have shadowOffset.
  58161. // shadowOffsetX: 0,
  58162. // shadowOffsetY: 2
  58163. },
  58164. handle: {
  58165. show: false,
  58166. /* eslint-disable */
  58167. 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
  58168. /* eslint-enable */
  58169. size: 45,
  58170. // handle margin is from symbol center to axis, which is stable when circular move.
  58171. margin: 50,
  58172. // color: '#1b8bbd'
  58173. // color: '#2f4554'
  58174. color: '#333',
  58175. shadowBlur: 3,
  58176. shadowColor: '#aaa',
  58177. shadowOffsetX: 0,
  58178. shadowOffsetY: 2,
  58179. // For mobile performance
  58180. throttle: 40
  58181. }
  58182. }
  58183. });
  58184. /*
  58185. * Licensed to the Apache Software Foundation (ASF) under one
  58186. * or more contributor license agreements. See the NOTICE file
  58187. * distributed with this work for additional information
  58188. * regarding copyright ownership. The ASF licenses this file
  58189. * to you under the Apache License, Version 2.0 (the
  58190. * "License"); you may not use this file except in compliance
  58191. * with the License. You may obtain a copy of the License at
  58192. *
  58193. * http://www.apache.org/licenses/LICENSE-2.0
  58194. *
  58195. * Unless required by applicable law or agreed to in writing,
  58196. * software distributed under the License is distributed on an
  58197. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58198. * KIND, either express or implied. See the License for the
  58199. * specific language governing permissions and limitations
  58200. * under the License.
  58201. */
  58202. var inner$10 = makeInner();
  58203. var each$15 = each$1;
  58204. /**
  58205. * @param {string} key
  58206. * @param {module:echarts/ExtensionAPI} api
  58207. * @param {Function} handler
  58208. * param: {string} currTrigger
  58209. * param: {Array.<number>} point
  58210. */
  58211. function register(key, api, handler) {
  58212. if (env$1.node) {
  58213. return;
  58214. }
  58215. var zr = api.getZr();
  58216. inner$10(zr).records || (inner$10(zr).records = {});
  58217. initGlobalListeners(zr, api);
  58218. var record = inner$10(zr).records[key] || (inner$10(zr).records[key] = {});
  58219. record.handler = handler;
  58220. }
  58221. function initGlobalListeners(zr, api) {
  58222. if (inner$10(zr).initialized) {
  58223. return;
  58224. }
  58225. inner$10(zr).initialized = true;
  58226. useHandler('click', curry(doEnter, 'click'));
  58227. useHandler('mousemove', curry(doEnter, 'mousemove'));
  58228. // useHandler('mouseout', onLeave);
  58229. useHandler('globalout', onLeave);
  58230. function useHandler(eventType, cb) {
  58231. zr.on(eventType, function (e) {
  58232. var dis = makeDispatchAction(api);
  58233. each$15(inner$10(zr).records, function (record) {
  58234. record && cb(record, e, dis.dispatchAction);
  58235. });
  58236. dispatchTooltipFinally(dis.pendings, api);
  58237. });
  58238. }
  58239. }
  58240. function dispatchTooltipFinally(pendings, api) {
  58241. var showLen = pendings.showTip.length;
  58242. var hideLen = pendings.hideTip.length;
  58243. var actuallyPayload;
  58244. if (showLen) {
  58245. actuallyPayload = pendings.showTip[showLen - 1];
  58246. }
  58247. else if (hideLen) {
  58248. actuallyPayload = pendings.hideTip[hideLen - 1];
  58249. }
  58250. if (actuallyPayload) {
  58251. actuallyPayload.dispatchAction = null;
  58252. api.dispatchAction(actuallyPayload);
  58253. }
  58254. }
  58255. function onLeave(record, e, dispatchAction) {
  58256. record.handler('leave', null, dispatchAction);
  58257. }
  58258. function doEnter(currTrigger, record, e, dispatchAction) {
  58259. record.handler(currTrigger, e, dispatchAction);
  58260. }
  58261. function makeDispatchAction(api) {
  58262. var pendings = {
  58263. showTip: [],
  58264. hideTip: []
  58265. };
  58266. // FIXME
  58267. // better approach?
  58268. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  58269. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  58270. // So we have to add "final stage" to merge those dispatched actions.
  58271. var dispatchAction = function (payload) {
  58272. var pendingList = pendings[payload.type];
  58273. if (pendingList) {
  58274. pendingList.push(payload);
  58275. }
  58276. else {
  58277. payload.dispatchAction = dispatchAction;
  58278. api.dispatchAction(payload);
  58279. }
  58280. };
  58281. return {
  58282. dispatchAction: dispatchAction,
  58283. pendings: pendings
  58284. };
  58285. }
  58286. /**
  58287. * @param {string} key
  58288. * @param {module:echarts/ExtensionAPI} api
  58289. */
  58290. function unregister(key, api) {
  58291. if (env$1.node) {
  58292. return;
  58293. }
  58294. var zr = api.getZr();
  58295. var record = (inner$10(zr).records || {})[key];
  58296. if (record) {
  58297. inner$10(zr).records[key] = null;
  58298. }
  58299. }
  58300. /*
  58301. * Licensed to the Apache Software Foundation (ASF) under one
  58302. * or more contributor license agreements. See the NOTICE file
  58303. * distributed with this work for additional information
  58304. * regarding copyright ownership. The ASF licenses this file
  58305. * to you under the Apache License, Version 2.0 (the
  58306. * "License"); you may not use this file except in compliance
  58307. * with the License. You may obtain a copy of the License at
  58308. *
  58309. * http://www.apache.org/licenses/LICENSE-2.0
  58310. *
  58311. * Unless required by applicable law or agreed to in writing,
  58312. * software distributed under the License is distributed on an
  58313. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58314. * KIND, either express or implied. See the License for the
  58315. * specific language governing permissions and limitations
  58316. * under the License.
  58317. */
  58318. var AxisPointerView = extendComponentView({
  58319. type: 'axisPointer',
  58320. render: function (globalAxisPointerModel, ecModel, api) {
  58321. var globalTooltipModel = ecModel.getComponent('tooltip');
  58322. var triggerOn = globalAxisPointerModel.get('triggerOn')
  58323. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  58324. // Register global listener in AxisPointerView to enable
  58325. // AxisPointerView to be independent to Tooltip.
  58326. register(
  58327. 'axisPointer',
  58328. api,
  58329. function (currTrigger, e, dispatchAction) {
  58330. // If 'none', it is not controlled by mouse totally.
  58331. if (triggerOn !== 'none'
  58332. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  58333. ) {
  58334. dispatchAction({
  58335. type: 'updateAxisPointer',
  58336. currTrigger: currTrigger,
  58337. x: e && e.offsetX,
  58338. y: e && e.offsetY
  58339. });
  58340. }
  58341. }
  58342. );
  58343. },
  58344. /**
  58345. * @override
  58346. */
  58347. remove: function (ecModel, api) {
  58348. unregister(api.getZr(), 'axisPointer');
  58349. AxisPointerView.superApply(this._model, 'remove', arguments);
  58350. },
  58351. /**
  58352. * @override
  58353. */
  58354. dispose: function (ecModel, api) {
  58355. unregister('axisPointer', api);
  58356. AxisPointerView.superApply(this._model, 'dispose', arguments);
  58357. }
  58358. });
  58359. /*
  58360. * Licensed to the Apache Software Foundation (ASF) under one
  58361. * or more contributor license agreements. See the NOTICE file
  58362. * distributed with this work for additional information
  58363. * regarding copyright ownership. The ASF licenses this file
  58364. * to you under the Apache License, Version 2.0 (the
  58365. * "License"); you may not use this file except in compliance
  58366. * with the License. You may obtain a copy of the License at
  58367. *
  58368. * http://www.apache.org/licenses/LICENSE-2.0
  58369. *
  58370. * Unless required by applicable law or agreed to in writing,
  58371. * software distributed under the License is distributed on an
  58372. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58373. * KIND, either express or implied. See the License for the
  58374. * specific language governing permissions and limitations
  58375. * under the License.
  58376. */
  58377. var inner$11 = makeInner();
  58378. var clone$4 = clone;
  58379. var bind$2 = bind;
  58380. /**
  58381. * Base axis pointer class in 2D.
  58382. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  58383. */
  58384. function BaseAxisPointer() {
  58385. }
  58386. BaseAxisPointer.prototype = {
  58387. /**
  58388. * @private
  58389. */
  58390. _group: null,
  58391. /**
  58392. * @private
  58393. */
  58394. _lastGraphicKey: null,
  58395. /**
  58396. * @private
  58397. */
  58398. _handle: null,
  58399. /**
  58400. * @private
  58401. */
  58402. _dragging: false,
  58403. /**
  58404. * @private
  58405. */
  58406. _lastValue: null,
  58407. /**
  58408. * @private
  58409. */
  58410. _lastStatus: null,
  58411. /**
  58412. * @private
  58413. */
  58414. _payloadInfo: null,
  58415. /**
  58416. * In px, arbitrary value. Do not set too small,
  58417. * no animation is ok for most cases.
  58418. * @protected
  58419. */
  58420. animationThreshold: 15,
  58421. /**
  58422. * @implement
  58423. */
  58424. render: function (axisModel, axisPointerModel, api, forceRender) {
  58425. var value = axisPointerModel.get('value');
  58426. var status = axisPointerModel.get('status');
  58427. // Bind them to `this`, not in closure, otherwise they will not
  58428. // be replaced when user calling setOption in not merge mode.
  58429. this._axisModel = axisModel;
  58430. this._axisPointerModel = axisPointerModel;
  58431. this._api = api;
  58432. // Optimize: `render` will be called repeatly during mouse move.
  58433. // So it is power consuming if performing `render` each time,
  58434. // especially on mobile device.
  58435. if (!forceRender
  58436. && this._lastValue === value
  58437. && this._lastStatus === status
  58438. ) {
  58439. return;
  58440. }
  58441. this._lastValue = value;
  58442. this._lastStatus = status;
  58443. var group = this._group;
  58444. var handle = this._handle;
  58445. if (!status || status === 'hide') {
  58446. // Do not clear here, for animation better.
  58447. group && group.hide();
  58448. handle && handle.hide();
  58449. return;
  58450. }
  58451. group && group.show();
  58452. handle && handle.show();
  58453. // Otherwise status is 'show'
  58454. var elOption = {};
  58455. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  58456. // Enable change axis pointer type.
  58457. var graphicKey = elOption.graphicKey;
  58458. if (graphicKey !== this._lastGraphicKey) {
  58459. this.clear(api);
  58460. }
  58461. this._lastGraphicKey = graphicKey;
  58462. var moveAnimation = this._moveAnimation
  58463. = this.determineAnimation(axisModel, axisPointerModel);
  58464. if (!group) {
  58465. group = this._group = new Group();
  58466. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  58467. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  58468. api.getZr().add(group);
  58469. }
  58470. else {
  58471. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  58472. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  58473. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  58474. }
  58475. updateMandatoryProps(group, axisPointerModel, true);
  58476. this._renderHandle(value);
  58477. },
  58478. /**
  58479. * @implement
  58480. */
  58481. remove: function (api) {
  58482. this.clear(api);
  58483. },
  58484. /**
  58485. * @implement
  58486. */
  58487. dispose: function (api) {
  58488. this.clear(api);
  58489. },
  58490. /**
  58491. * @protected
  58492. */
  58493. determineAnimation: function (axisModel, axisPointerModel) {
  58494. var animation = axisPointerModel.get('animation');
  58495. var axis = axisModel.axis;
  58496. var isCategoryAxis = axis.type === 'category';
  58497. var useSnap = axisPointerModel.get('snap');
  58498. // Value axis without snap always do not snap.
  58499. if (!useSnap && !isCategoryAxis) {
  58500. return false;
  58501. }
  58502. if (animation === 'auto' || animation == null) {
  58503. var animationThreshold = this.animationThreshold;
  58504. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  58505. return true;
  58506. }
  58507. // It is important to auto animation when snap used. Consider if there is
  58508. // a dataZoom, animation will be disabled when too many points exist, while
  58509. // it will be enabled for better visual effect when little points exist.
  58510. if (useSnap) {
  58511. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  58512. var axisExtent = axis.getExtent();
  58513. // Approximate band width
  58514. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  58515. }
  58516. return false;
  58517. }
  58518. return animation === true;
  58519. },
  58520. /**
  58521. * add {pointer, label, graphicKey} to elOption
  58522. * @protected
  58523. */
  58524. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  58525. // Shoule be implemenented by sub-class.
  58526. },
  58527. /**
  58528. * @protected
  58529. */
  58530. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  58531. var pointerOption = elOption.pointer;
  58532. if (pointerOption) {
  58533. var pointerEl = inner$11(group).pointerEl = new graphic[pointerOption.type](
  58534. clone$4(elOption.pointer)
  58535. );
  58536. group.add(pointerEl);
  58537. }
  58538. },
  58539. /**
  58540. * @protected
  58541. */
  58542. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  58543. if (elOption.label) {
  58544. var labelEl = inner$11(group).labelEl = new Rect(
  58545. clone$4(elOption.label)
  58546. );
  58547. group.add(labelEl);
  58548. updateLabelShowHide(labelEl, axisPointerModel);
  58549. }
  58550. },
  58551. /**
  58552. * @protected
  58553. */
  58554. updatePointerEl: function (group, elOption, updateProps$$1) {
  58555. var pointerEl = inner$11(group).pointerEl;
  58556. if (pointerEl) {
  58557. pointerEl.setStyle(elOption.pointer.style);
  58558. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  58559. }
  58560. },
  58561. /**
  58562. * @protected
  58563. */
  58564. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  58565. var labelEl = inner$11(group).labelEl;
  58566. if (labelEl) {
  58567. labelEl.setStyle(elOption.label.style);
  58568. updateProps$$1(labelEl, {
  58569. // Consider text length change in vertical axis, animation should
  58570. // be used on shape, otherwise the effect will be weird.
  58571. shape: elOption.label.shape,
  58572. position: elOption.label.position
  58573. });
  58574. updateLabelShowHide(labelEl, axisPointerModel);
  58575. }
  58576. },
  58577. /**
  58578. * @private
  58579. */
  58580. _renderHandle: function (value) {
  58581. if (this._dragging || !this.updateHandleTransform) {
  58582. return;
  58583. }
  58584. var axisPointerModel = this._axisPointerModel;
  58585. var zr = this._api.getZr();
  58586. var handle = this._handle;
  58587. var handleModel = axisPointerModel.getModel('handle');
  58588. var status = axisPointerModel.get('status');
  58589. if (!handleModel.get('show') || !status || status === 'hide') {
  58590. handle && zr.remove(handle);
  58591. this._handle = null;
  58592. return;
  58593. }
  58594. var isInit;
  58595. if (!this._handle) {
  58596. isInit = true;
  58597. handle = this._handle = createIcon(
  58598. handleModel.get('icon'),
  58599. {
  58600. cursor: 'move',
  58601. draggable: true,
  58602. onmousemove: function (e) {
  58603. // Fot mobile devicem, prevent screen slider on the button.
  58604. stop(e.event);
  58605. },
  58606. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  58607. drift: bind$2(this._onHandleDragMove, this),
  58608. ondragend: bind$2(this._onHandleDragEnd, this)
  58609. }
  58610. );
  58611. zr.add(handle);
  58612. }
  58613. updateMandatoryProps(handle, axisPointerModel, false);
  58614. // update style
  58615. var includeStyles = [
  58616. 'color', 'borderColor', 'borderWidth', 'opacity',
  58617. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  58618. ];
  58619. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  58620. // update position
  58621. var handleSize = handleModel.get('size');
  58622. if (!isArray(handleSize)) {
  58623. handleSize = [handleSize, handleSize];
  58624. }
  58625. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  58626. createOrUpdate(
  58627. this,
  58628. '_doDispatchAxisPointer',
  58629. handleModel.get('throttle') || 0,
  58630. 'fixRate'
  58631. );
  58632. this._moveHandleToValue(value, isInit);
  58633. },
  58634. /**
  58635. * @private
  58636. */
  58637. _moveHandleToValue: function (value, isInit) {
  58638. updateProps$1(
  58639. this._axisPointerModel,
  58640. !isInit && this._moveAnimation,
  58641. this._handle,
  58642. getHandleTransProps(this.getHandleTransform(
  58643. value, this._axisModel, this._axisPointerModel
  58644. ))
  58645. );
  58646. },
  58647. /**
  58648. * @private
  58649. */
  58650. _onHandleDragMove: function (dx, dy) {
  58651. var handle = this._handle;
  58652. if (!handle) {
  58653. return;
  58654. }
  58655. this._dragging = true;
  58656. // Persistent for throttle.
  58657. var trans = this.updateHandleTransform(
  58658. getHandleTransProps(handle),
  58659. [dx, dy],
  58660. this._axisModel,
  58661. this._axisPointerModel
  58662. );
  58663. this._payloadInfo = trans;
  58664. handle.stopAnimation();
  58665. handle.attr(getHandleTransProps(trans));
  58666. inner$11(handle).lastProp = null;
  58667. this._doDispatchAxisPointer();
  58668. },
  58669. /**
  58670. * Throttled method.
  58671. * @private
  58672. */
  58673. _doDispatchAxisPointer: function () {
  58674. var handle = this._handle;
  58675. if (!handle) {
  58676. return;
  58677. }
  58678. var payloadInfo = this._payloadInfo;
  58679. var axisModel = this._axisModel;
  58680. this._api.dispatchAction({
  58681. type: 'updateAxisPointer',
  58682. x: payloadInfo.cursorPoint[0],
  58683. y: payloadInfo.cursorPoint[1],
  58684. tooltipOption: payloadInfo.tooltipOption,
  58685. axesInfo: [{
  58686. axisDim: axisModel.axis.dim,
  58687. axisIndex: axisModel.componentIndex
  58688. }]
  58689. });
  58690. },
  58691. /**
  58692. * @private
  58693. */
  58694. _onHandleDragEnd: function (moveAnimation) {
  58695. this._dragging = false;
  58696. var handle = this._handle;
  58697. if (!handle) {
  58698. return;
  58699. }
  58700. var value = this._axisPointerModel.get('value');
  58701. // Consider snap or categroy axis, handle may be not consistent with
  58702. // axisPointer. So move handle to align the exact value position when
  58703. // drag ended.
  58704. this._moveHandleToValue(value);
  58705. // For the effect: tooltip will be shown when finger holding on handle
  58706. // button, and will be hidden after finger left handle button.
  58707. this._api.dispatchAction({
  58708. type: 'hideTip'
  58709. });
  58710. },
  58711. /**
  58712. * Should be implemenented by sub-class if support `handle`.
  58713. * @protected
  58714. * @param {number} value
  58715. * @param {module:echarts/model/Model} axisModel
  58716. * @param {module:echarts/model/Model} axisPointerModel
  58717. * @return {Object} {position: [x, y], rotation: 0}
  58718. */
  58719. getHandleTransform: null,
  58720. /**
  58721. * * Should be implemenented by sub-class if support `handle`.
  58722. * @protected
  58723. * @param {Object} transform {position, rotation}
  58724. * @param {Array.<number>} delta [dx, dy]
  58725. * @param {module:echarts/model/Model} axisModel
  58726. * @param {module:echarts/model/Model} axisPointerModel
  58727. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  58728. */
  58729. updateHandleTransform: null,
  58730. /**
  58731. * @private
  58732. */
  58733. clear: function (api) {
  58734. this._lastValue = null;
  58735. this._lastStatus = null;
  58736. var zr = api.getZr();
  58737. var group = this._group;
  58738. var handle = this._handle;
  58739. if (zr && group) {
  58740. this._lastGraphicKey = null;
  58741. group && zr.remove(group);
  58742. handle && zr.remove(handle);
  58743. this._group = null;
  58744. this._handle = null;
  58745. this._payloadInfo = null;
  58746. }
  58747. },
  58748. /**
  58749. * @protected
  58750. */
  58751. doClear: function () {
  58752. // Implemented by sub-class if necessary.
  58753. },
  58754. /**
  58755. * @protected
  58756. * @param {Array.<number>} xy
  58757. * @param {Array.<number>} wh
  58758. * @param {number} [xDimIndex=0] or 1
  58759. */
  58760. buildLabel: function (xy, wh, xDimIndex) {
  58761. xDimIndex = xDimIndex || 0;
  58762. return {
  58763. x: xy[xDimIndex],
  58764. y: xy[1 - xDimIndex],
  58765. width: wh[xDimIndex],
  58766. height: wh[1 - xDimIndex]
  58767. };
  58768. }
  58769. };
  58770. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  58771. function updateProps$1(animationModel, moveAnimation, el, props) {
  58772. // Animation optimize.
  58773. if (!propsEqual(inner$11(el).lastProp, props)) {
  58774. inner$11(el).lastProp = props;
  58775. moveAnimation
  58776. ? updateProps(el, props, animationModel)
  58777. : (el.stopAnimation(), el.attr(props));
  58778. }
  58779. }
  58780. function propsEqual(lastProps, newProps) {
  58781. if (isObject$1(lastProps) && isObject$1(newProps)) {
  58782. var equals = true;
  58783. each$1(newProps, function (item, key) {
  58784. equals = equals && propsEqual(lastProps[key], item);
  58785. });
  58786. return !!equals;
  58787. }
  58788. else {
  58789. return lastProps === newProps;
  58790. }
  58791. }
  58792. function updateLabelShowHide(labelEl, axisPointerModel) {
  58793. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  58794. }
  58795. function getHandleTransProps(trans) {
  58796. return {
  58797. position: trans.position.slice(),
  58798. rotation: trans.rotation || 0
  58799. };
  58800. }
  58801. function updateMandatoryProps(group, axisPointerModel, silent) {
  58802. var z = axisPointerModel.get('z');
  58803. var zlevel = axisPointerModel.get('zlevel');
  58804. group && group.traverse(function (el) {
  58805. if (el.type !== 'group') {
  58806. z != null && (el.z = z);
  58807. zlevel != null && (el.zlevel = zlevel);
  58808. el.silent = silent;
  58809. }
  58810. });
  58811. }
  58812. enableClassExtend(BaseAxisPointer);
  58813. /*
  58814. * Licensed to the Apache Software Foundation (ASF) under one
  58815. * or more contributor license agreements. See the NOTICE file
  58816. * distributed with this work for additional information
  58817. * regarding copyright ownership. The ASF licenses this file
  58818. * to you under the Apache License, Version 2.0 (the
  58819. * "License"); you may not use this file except in compliance
  58820. * with the License. You may obtain a copy of the License at
  58821. *
  58822. * http://www.apache.org/licenses/LICENSE-2.0
  58823. *
  58824. * Unless required by applicable law or agreed to in writing,
  58825. * software distributed under the License is distributed on an
  58826. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58827. * KIND, either express or implied. See the License for the
  58828. * specific language governing permissions and limitations
  58829. * under the License.
  58830. */
  58831. /**
  58832. * @param {module:echarts/model/Model} axisPointerModel
  58833. */
  58834. function buildElStyle(axisPointerModel) {
  58835. var axisPointerType = axisPointerModel.get('type');
  58836. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  58837. var style;
  58838. if (axisPointerType === 'line') {
  58839. style = styleModel.getLineStyle();
  58840. style.fill = null;
  58841. }
  58842. else if (axisPointerType === 'shadow') {
  58843. style = styleModel.getAreaStyle();
  58844. style.stroke = null;
  58845. }
  58846. return style;
  58847. }
  58848. /**
  58849. * @param {Function} labelPos {align, verticalAlign, position}
  58850. */
  58851. function buildLabelElOption(
  58852. elOption, axisModel, axisPointerModel, api, labelPos
  58853. ) {
  58854. var value = axisPointerModel.get('value');
  58855. var text = getValueLabel(
  58856. value, axisModel.axis, axisModel.ecModel,
  58857. axisPointerModel.get('seriesDataIndices'),
  58858. {
  58859. precision: axisPointerModel.get('label.precision'),
  58860. formatter: axisPointerModel.get('label.formatter')
  58861. }
  58862. );
  58863. var labelModel = axisPointerModel.getModel('label');
  58864. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  58865. var font = labelModel.getFont();
  58866. var textRect = getBoundingRect(text, font);
  58867. var position = labelPos.position;
  58868. var width = textRect.width + paddings[1] + paddings[3];
  58869. var height = textRect.height + paddings[0] + paddings[2];
  58870. // Adjust by align.
  58871. var align = labelPos.align;
  58872. align === 'right' && (position[0] -= width);
  58873. align === 'center' && (position[0] -= width / 2);
  58874. var verticalAlign = labelPos.verticalAlign;
  58875. verticalAlign === 'bottom' && (position[1] -= height);
  58876. verticalAlign === 'middle' && (position[1] -= height / 2);
  58877. // Not overflow ec container
  58878. confineInContainer(position, width, height, api);
  58879. var bgColor = labelModel.get('backgroundColor');
  58880. if (!bgColor || bgColor === 'auto') {
  58881. bgColor = axisModel.get('axisLine.lineStyle.color');
  58882. }
  58883. elOption.label = {
  58884. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  58885. position: position.slice(),
  58886. // TODO: rich
  58887. style: {
  58888. text: text,
  58889. textFont: font,
  58890. textFill: labelModel.getTextColor(),
  58891. textPosition: 'inside',
  58892. fill: bgColor,
  58893. stroke: labelModel.get('borderColor') || 'transparent',
  58894. lineWidth: labelModel.get('borderWidth') || 0,
  58895. shadowBlur: labelModel.get('shadowBlur'),
  58896. shadowColor: labelModel.get('shadowColor'),
  58897. shadowOffsetX: labelModel.get('shadowOffsetX'),
  58898. shadowOffsetY: labelModel.get('shadowOffsetY')
  58899. },
  58900. // Lable should be over axisPointer.
  58901. z2: 10
  58902. };
  58903. }
  58904. // Do not overflow ec container
  58905. function confineInContainer(position, width, height, api) {
  58906. var viewWidth = api.getWidth();
  58907. var viewHeight = api.getHeight();
  58908. position[0] = Math.min(position[0] + width, viewWidth) - width;
  58909. position[1] = Math.min(position[1] + height, viewHeight) - height;
  58910. position[0] = Math.max(position[0], 0);
  58911. position[1] = Math.max(position[1], 0);
  58912. }
  58913. /**
  58914. * @param {number} value
  58915. * @param {module:echarts/coord/Axis} axis
  58916. * @param {module:echarts/model/Global} ecModel
  58917. * @param {Object} opt
  58918. * @param {Array.<Object>} seriesDataIndices
  58919. * @param {number|string} opt.precision 'auto' or a number
  58920. * @param {string|Function} opt.formatter label formatter
  58921. */
  58922. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  58923. value = axis.scale.parse(value);
  58924. var text = axis.scale.getLabel(
  58925. // If `precision` is set, width can be fixed (like '12.00500'), which
  58926. // helps to debounce when when moving label.
  58927. value, {precision: opt.precision}
  58928. );
  58929. var formatter = opt.formatter;
  58930. if (formatter) {
  58931. var params = {
  58932. value: getAxisRawValue(axis, value),
  58933. seriesData: []
  58934. };
  58935. each$1(seriesDataIndices, function (idxItem) {
  58936. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  58937. var dataIndex = idxItem.dataIndexInside;
  58938. var dataParams = series && series.getDataParams(dataIndex);
  58939. dataParams && params.seriesData.push(dataParams);
  58940. });
  58941. if (isString(formatter)) {
  58942. text = formatter.replace('{value}', text);
  58943. }
  58944. else if (isFunction$1(formatter)) {
  58945. text = formatter(params);
  58946. }
  58947. }
  58948. return text;
  58949. }
  58950. /**
  58951. * @param {module:echarts/coord/Axis} axis
  58952. * @param {number} value
  58953. * @param {Object} layoutInfo {
  58954. * rotation, position, labelOffset, labelDirection, labelMargin
  58955. * }
  58956. */
  58957. function getTransformedPosition(axis, value, layoutInfo) {
  58958. var transform = create$1();
  58959. rotate(transform, transform, layoutInfo.rotation);
  58960. translate(transform, transform, layoutInfo.position);
  58961. return applyTransform$1([
  58962. axis.dataToCoord(value),
  58963. (layoutInfo.labelOffset || 0)
  58964. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  58965. ], transform);
  58966. }
  58967. function buildCartesianSingleLabelElOption(
  58968. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  58969. ) {
  58970. var textLayout = AxisBuilder.innerTextLayout(
  58971. layoutInfo.rotation, 0, layoutInfo.labelDirection
  58972. );
  58973. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  58974. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  58975. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  58976. align: textLayout.textAlign,
  58977. verticalAlign: textLayout.textVerticalAlign
  58978. });
  58979. }
  58980. /**
  58981. * @param {Array.<number>} p1
  58982. * @param {Array.<number>} p2
  58983. * @param {number} [xDimIndex=0] or 1
  58984. */
  58985. function makeLineShape(p1, p2, xDimIndex) {
  58986. xDimIndex = xDimIndex || 0;
  58987. return {
  58988. x1: p1[xDimIndex],
  58989. y1: p1[1 - xDimIndex],
  58990. x2: p2[xDimIndex],
  58991. y2: p2[1 - xDimIndex]
  58992. };
  58993. }
  58994. /**
  58995. * @param {Array.<number>} xy
  58996. * @param {Array.<number>} wh
  58997. * @param {number} [xDimIndex=0] or 1
  58998. */
  58999. function makeRectShape(xy, wh, xDimIndex) {
  59000. xDimIndex = xDimIndex || 0;
  59001. return {
  59002. x: xy[xDimIndex],
  59003. y: xy[1 - xDimIndex],
  59004. width: wh[xDimIndex],
  59005. height: wh[1 - xDimIndex]
  59006. };
  59007. }
  59008. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  59009. return {
  59010. cx: cx,
  59011. cy: cy,
  59012. r0: r0,
  59013. r: r,
  59014. startAngle: startAngle,
  59015. endAngle: endAngle,
  59016. clockwise: true
  59017. };
  59018. }
  59019. /*
  59020. * Licensed to the Apache Software Foundation (ASF) under one
  59021. * or more contributor license agreements. See the NOTICE file
  59022. * distributed with this work for additional information
  59023. * regarding copyright ownership. The ASF licenses this file
  59024. * to you under the Apache License, Version 2.0 (the
  59025. * "License"); you may not use this file except in compliance
  59026. * with the License. You may obtain a copy of the License at
  59027. *
  59028. * http://www.apache.org/licenses/LICENSE-2.0
  59029. *
  59030. * Unless required by applicable law or agreed to in writing,
  59031. * software distributed under the License is distributed on an
  59032. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59033. * KIND, either express or implied. See the License for the
  59034. * specific language governing permissions and limitations
  59035. * under the License.
  59036. */
  59037. var CartesianAxisPointer = BaseAxisPointer.extend({
  59038. /**
  59039. * @override
  59040. */
  59041. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  59042. var axis = axisModel.axis;
  59043. var grid = axis.grid;
  59044. var axisPointerType = axisPointerModel.get('type');
  59045. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  59046. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  59047. if (axisPointerType && axisPointerType !== 'none') {
  59048. var elStyle = buildElStyle(axisPointerModel);
  59049. var pointerOption = pointerShapeBuilder[axisPointerType](
  59050. axis, pixelValue, otherExtent, elStyle
  59051. );
  59052. pointerOption.style = elStyle;
  59053. elOption.graphicKey = pointerOption.type;
  59054. elOption.pointer = pointerOption;
  59055. }
  59056. var layoutInfo = layout$1(grid.model, axisModel);
  59057. buildCartesianSingleLabelElOption(
  59058. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  59059. );
  59060. },
  59061. /**
  59062. * @override
  59063. */
  59064. getHandleTransform: function (value, axisModel, axisPointerModel) {
  59065. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  59066. labelInside: false
  59067. });
  59068. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  59069. return {
  59070. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  59071. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  59072. };
  59073. },
  59074. /**
  59075. * @override
  59076. */
  59077. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  59078. var axis = axisModel.axis;
  59079. var grid = axis.grid;
  59080. var axisExtent = axis.getGlobalExtent(true);
  59081. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  59082. var dimIndex = axis.dim === 'x' ? 0 : 1;
  59083. var currPosition = transform.position;
  59084. currPosition[dimIndex] += delta[dimIndex];
  59085. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  59086. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  59087. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  59088. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  59089. cursorPoint[dimIndex] = currPosition[dimIndex];
  59090. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  59091. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  59092. return {
  59093. position: currPosition,
  59094. rotation: transform.rotation,
  59095. cursorPoint: cursorPoint,
  59096. tooltipOption: tooltipOptions[dimIndex]
  59097. };
  59098. }
  59099. });
  59100. function getCartesian(grid, axis) {
  59101. var opt = {};
  59102. opt[axis.dim + 'AxisIndex'] = axis.index;
  59103. return grid.getCartesian(opt);
  59104. }
  59105. var pointerShapeBuilder = {
  59106. line: function (axis, pixelValue, otherExtent, elStyle) {
  59107. var targetShape = makeLineShape(
  59108. [pixelValue, otherExtent[0]],
  59109. [pixelValue, otherExtent[1]],
  59110. getAxisDimIndex(axis)
  59111. );
  59112. subPixelOptimizeLine({
  59113. shape: targetShape,
  59114. style: elStyle
  59115. });
  59116. return {
  59117. type: 'Line',
  59118. shape: targetShape
  59119. };
  59120. },
  59121. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  59122. var bandWidth = Math.max(1, axis.getBandWidth());
  59123. var span = otherExtent[1] - otherExtent[0];
  59124. return {
  59125. type: 'Rect',
  59126. shape: makeRectShape(
  59127. [pixelValue - bandWidth / 2, otherExtent[0]],
  59128. [bandWidth, span],
  59129. getAxisDimIndex(axis)
  59130. )
  59131. };
  59132. }
  59133. };
  59134. function getAxisDimIndex(axis) {
  59135. return axis.dim === 'x' ? 0 : 1;
  59136. }
  59137. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  59138. /*
  59139. * Licensed to the Apache Software Foundation (ASF) under one
  59140. * or more contributor license agreements. See the NOTICE file
  59141. * distributed with this work for additional information
  59142. * regarding copyright ownership. The ASF licenses this file
  59143. * to you under the Apache License, Version 2.0 (the
  59144. * "License"); you may not use this file except in compliance
  59145. * with the License. You may obtain a copy of the License at
  59146. *
  59147. * http://www.apache.org/licenses/LICENSE-2.0
  59148. *
  59149. * Unless required by applicable law or agreed to in writing,
  59150. * software distributed under the License is distributed on an
  59151. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59152. * KIND, either express or implied. See the License for the
  59153. * specific language governing permissions and limitations
  59154. * under the License.
  59155. */
  59156. // CartesianAxisPointer is not supposed to be required here. But consider
  59157. // echarts.simple.js and online build tooltip, which only require gridSimple,
  59158. // CartesianAxisPointer should be able to required somewhere.
  59159. registerPreprocessor(function (option) {
  59160. // Always has a global axisPointerModel for default setting.
  59161. if (option) {
  59162. (!option.axisPointer || option.axisPointer.length === 0)
  59163. && (option.axisPointer = {});
  59164. var link = option.axisPointer.link;
  59165. // Normalize to array to avoid object mergin. But if link
  59166. // is not set, remain null/undefined, otherwise it will
  59167. // override existent link setting.
  59168. if (link && !isArray(link)) {
  59169. option.axisPointer.link = [link];
  59170. }
  59171. }
  59172. });
  59173. // This process should proformed after coordinate systems created
  59174. // and series data processed. So put it on statistic processing stage.
  59175. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  59176. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  59177. // allAxesInfo should be updated when setOption performed.
  59178. ecModel.getComponent('axisPointer').coordSysAxesInfo
  59179. = collect(ecModel, api);
  59180. });
  59181. // Broadcast to all views.
  59182. registerAction({
  59183. type: 'updateAxisPointer',
  59184. event: 'updateAxisPointer',
  59185. update: ':updateAxisPointer'
  59186. }, axisTrigger);
  59187. /*
  59188. * Licensed to the Apache Software Foundation (ASF) under one
  59189. * or more contributor license agreements. See the NOTICE file
  59190. * distributed with this work for additional information
  59191. * regarding copyright ownership. The ASF licenses this file
  59192. * to you under the Apache License, Version 2.0 (the
  59193. * "License"); you may not use this file except in compliance
  59194. * with the License. You may obtain a copy of the License at
  59195. *
  59196. * http://www.apache.org/licenses/LICENSE-2.0
  59197. *
  59198. * Unless required by applicable law or agreed to in writing,
  59199. * software distributed under the License is distributed on an
  59200. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59201. * KIND, either express or implied. See the License for the
  59202. * specific language governing permissions and limitations
  59203. * under the License.
  59204. */
  59205. var XY = ['x', 'y'];
  59206. var WH = ['width', 'height'];
  59207. var SingleAxisPointer = BaseAxisPointer.extend({
  59208. /**
  59209. * @override
  59210. */
  59211. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  59212. var axis = axisModel.axis;
  59213. var coordSys = axis.coordinateSystem;
  59214. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  59215. var pixelValue = coordSys.dataToPoint(value)[0];
  59216. var axisPointerType = axisPointerModel.get('type');
  59217. if (axisPointerType && axisPointerType !== 'none') {
  59218. var elStyle = buildElStyle(axisPointerModel);
  59219. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  59220. axis, pixelValue, otherExtent, elStyle
  59221. );
  59222. pointerOption.style = elStyle;
  59223. elOption.graphicKey = pointerOption.type;
  59224. elOption.pointer = pointerOption;
  59225. }
  59226. var layoutInfo = layout$2(axisModel);
  59227. buildCartesianSingleLabelElOption(
  59228. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  59229. );
  59230. },
  59231. /**
  59232. * @override
  59233. */
  59234. getHandleTransform: function (value, axisModel, axisPointerModel) {
  59235. var layoutInfo = layout$2(axisModel, {labelInside: false});
  59236. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  59237. return {
  59238. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  59239. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  59240. };
  59241. },
  59242. /**
  59243. * @override
  59244. */
  59245. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  59246. var axis = axisModel.axis;
  59247. var coordSys = axis.coordinateSystem;
  59248. var dimIndex = getPointDimIndex(axis);
  59249. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  59250. var currPosition = transform.position;
  59251. currPosition[dimIndex] += delta[dimIndex];
  59252. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  59253. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  59254. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  59255. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  59256. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  59257. cursorPoint[dimIndex] = currPosition[dimIndex];
  59258. return {
  59259. position: currPosition,
  59260. rotation: transform.rotation,
  59261. cursorPoint: cursorPoint,
  59262. tooltipOption: {
  59263. verticalAlign: 'middle'
  59264. }
  59265. };
  59266. }
  59267. });
  59268. var pointerShapeBuilder$1 = {
  59269. line: function (axis, pixelValue, otherExtent, elStyle) {
  59270. var targetShape = makeLineShape(
  59271. [pixelValue, otherExtent[0]],
  59272. [pixelValue, otherExtent[1]],
  59273. getPointDimIndex(axis)
  59274. );
  59275. subPixelOptimizeLine({
  59276. shape: targetShape,
  59277. style: elStyle
  59278. });
  59279. return {
  59280. type: 'Line',
  59281. shape: targetShape
  59282. };
  59283. },
  59284. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  59285. var bandWidth = axis.getBandWidth();
  59286. var span = otherExtent[1] - otherExtent[0];
  59287. return {
  59288. type: 'Rect',
  59289. shape: makeRectShape(
  59290. [pixelValue - bandWidth / 2, otherExtent[0]],
  59291. [bandWidth, span],
  59292. getPointDimIndex(axis)
  59293. )
  59294. };
  59295. }
  59296. };
  59297. function getPointDimIndex(axis) {
  59298. return axis.isHorizontal() ? 0 : 1;
  59299. }
  59300. function getGlobalExtent(coordSys, dimIndex) {
  59301. var rect = coordSys.getRect();
  59302. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  59303. }
  59304. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  59305. /*
  59306. * Licensed to the Apache Software Foundation (ASF) under one
  59307. * or more contributor license agreements. See the NOTICE file
  59308. * distributed with this work for additional information
  59309. * regarding copyright ownership. The ASF licenses this file
  59310. * to you under the Apache License, Version 2.0 (the
  59311. * "License"); you may not use this file except in compliance
  59312. * with the License. You may obtain a copy of the License at
  59313. *
  59314. * http://www.apache.org/licenses/LICENSE-2.0
  59315. *
  59316. * Unless required by applicable law or agreed to in writing,
  59317. * software distributed under the License is distributed on an
  59318. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59319. * KIND, either express or implied. See the License for the
  59320. * specific language governing permissions and limitations
  59321. * under the License.
  59322. */
  59323. extendComponentView({
  59324. type: 'single'
  59325. });
  59326. /*
  59327. * Licensed to the Apache Software Foundation (ASF) under one
  59328. * or more contributor license agreements. See the NOTICE file
  59329. * distributed with this work for additional information
  59330. * regarding copyright ownership. The ASF licenses this file
  59331. * to you under the Apache License, Version 2.0 (the
  59332. * "License"); you may not use this file except in compliance
  59333. * with the License. You may obtain a copy of the License at
  59334. *
  59335. * http://www.apache.org/licenses/LICENSE-2.0
  59336. *
  59337. * Unless required by applicable law or agreed to in writing,
  59338. * software distributed under the License is distributed on an
  59339. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59340. * KIND, either express or implied. See the License for the
  59341. * specific language governing permissions and limitations
  59342. * under the License.
  59343. */
  59344. /**
  59345. * @file Define the themeRiver view's series model
  59346. * @author Deqing Li(annong035@gmail.com)
  59347. */
  59348. var DATA_NAME_INDEX = 2;
  59349. var ThemeRiverSeries = SeriesModel.extend({
  59350. type: 'series.themeRiver',
  59351. dependencies: ['singleAxis'],
  59352. /**
  59353. * @readOnly
  59354. * @type {module:zrender/core/util#HashMap}
  59355. */
  59356. nameMap: null,
  59357. /**
  59358. * @override
  59359. */
  59360. init: function (option) {
  59361. // eslint-disable-next-line
  59362. ThemeRiverSeries.superApply(this, 'init', arguments);
  59363. // Put this function here is for the sake of consistency of code style.
  59364. // Enable legend selection for each data item
  59365. // Use a function instead of direct access because data reference may changed
  59366. this.legendDataProvider = function () {
  59367. return this.getRawData();
  59368. };
  59369. },
  59370. /**
  59371. * If there is no value of a certain point in the time for some event,set it value to 0.
  59372. *
  59373. * @param {Array} data initial data in the option
  59374. * @return {Array}
  59375. */
  59376. fixData: function (data) {
  59377. var rawDataLength = data.length;
  59378. // grouped data by name
  59379. var groupResult = groupData(data, function (item) {
  59380. return item[2];
  59381. });
  59382. var layData = [];
  59383. groupResult.buckets.each(function (items, key) {
  59384. layData.push({name: key, dataList: items});
  59385. });
  59386. var layerNum = layData.length;
  59387. var largestLayer = -1;
  59388. var index = -1;
  59389. for (var i = 0; i < layerNum; ++i) {
  59390. var len = layData[i].dataList.length;
  59391. if (len > largestLayer) {
  59392. largestLayer = len;
  59393. index = i;
  59394. }
  59395. }
  59396. for (var k = 0; k < layerNum; ++k) {
  59397. if (k === index) {
  59398. continue;
  59399. }
  59400. var name = layData[k].name;
  59401. for (var j = 0; j < largestLayer; ++j) {
  59402. var timeValue = layData[index].dataList[j][0];
  59403. var length = layData[k].dataList.length;
  59404. var keyIndex = -1;
  59405. for (var l = 0; l < length; ++l) {
  59406. var value = layData[k].dataList[l][0];
  59407. if (value === timeValue) {
  59408. keyIndex = l;
  59409. break;
  59410. }
  59411. }
  59412. if (keyIndex === -1) {
  59413. data[rawDataLength] = [];
  59414. data[rawDataLength][0] = timeValue;
  59415. data[rawDataLength][1] = 0;
  59416. data[rawDataLength][2] = name;
  59417. rawDataLength++;
  59418. }
  59419. }
  59420. }
  59421. return data;
  59422. },
  59423. /**
  59424. * @override
  59425. * @param {Object} option the initial option that user gived
  59426. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  59427. * @return {module:echarts/data/List}
  59428. */
  59429. getInitialData: function (option, ecModel) {
  59430. var singleAxisModel = ecModel.queryComponents({
  59431. mainType: 'singleAxis',
  59432. index: this.get('singleAxisIndex'),
  59433. id: this.get('singleAxisId')
  59434. })[0];
  59435. var axisType = singleAxisModel.get('type');
  59436. // filter the data item with the value of label is undefined
  59437. var filterData = filter(option.data, function (dataItem) {
  59438. return dataItem[2] !== undefined;
  59439. });
  59440. // ??? TODO design a stage to transfer data for themeRiver and lines?
  59441. var data = this.fixData(filterData || []);
  59442. var nameList = [];
  59443. var nameMap = this.nameMap = createHashMap();
  59444. var count = 0;
  59445. for (var i = 0; i < data.length; ++i) {
  59446. nameList.push(data[i][DATA_NAME_INDEX]);
  59447. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  59448. nameMap.set(data[i][DATA_NAME_INDEX], count);
  59449. count++;
  59450. }
  59451. }
  59452. var dimensionsInfo = createDimensions(data, {
  59453. coordDimensions: ['single'],
  59454. dimensionsDefine: [
  59455. {
  59456. name: 'time',
  59457. type: getDimensionTypeByAxis(axisType)
  59458. },
  59459. {
  59460. name: 'value',
  59461. type: 'float'
  59462. },
  59463. {
  59464. name: 'name',
  59465. type: 'ordinal'
  59466. }
  59467. ],
  59468. encodeDefine: {
  59469. single: 0,
  59470. value: 1,
  59471. itemName: 2
  59472. }
  59473. });
  59474. var list = new List(dimensionsInfo, this);
  59475. list.initData(data);
  59476. return list;
  59477. },
  59478. /**
  59479. * The raw data is divided into multiple layers and each layer
  59480. * has same name.
  59481. *
  59482. * @return {Array.<Array.<number>>}
  59483. */
  59484. getLayerSeries: function () {
  59485. var data = this.getData();
  59486. var lenCount = data.count();
  59487. var indexArr = [];
  59488. for (var i = 0; i < lenCount; ++i) {
  59489. indexArr[i] = i;
  59490. }
  59491. var timeDim = data.mapDimension('single');
  59492. // data group by name
  59493. var groupResult = groupData(indexArr, function (index) {
  59494. return data.get('name', index);
  59495. });
  59496. var layerSeries = [];
  59497. groupResult.buckets.each(function (items, key) {
  59498. items.sort(function (index1, index2) {
  59499. return data.get(timeDim, index1) - data.get(timeDim, index2);
  59500. });
  59501. layerSeries.push({name: key, indices: items});
  59502. });
  59503. return layerSeries;
  59504. },
  59505. /**
  59506. * Get data indices for show tooltip content
  59507. *
  59508. * @param {Array.<string>|string} dim single coordinate dimension
  59509. * @param {number} value axis value
  59510. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  59511. * the themeRiver.
  59512. * @return {Object} {dataIndices, nestestValue}
  59513. */
  59514. getAxisTooltipData: function (dim, value, baseAxis) {
  59515. if (!isArray(dim)) {
  59516. dim = dim ? [dim] : [];
  59517. }
  59518. var data = this.getData();
  59519. var layerSeries = this.getLayerSeries();
  59520. var indices = [];
  59521. var layerNum = layerSeries.length;
  59522. var nestestValue;
  59523. for (var i = 0; i < layerNum; ++i) {
  59524. var minDist = Number.MAX_VALUE;
  59525. var nearestIdx = -1;
  59526. var pointNum = layerSeries[i].indices.length;
  59527. for (var j = 0; j < pointNum; ++j) {
  59528. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  59529. var dist = Math.abs(theValue - value);
  59530. if (dist <= minDist) {
  59531. nestestValue = theValue;
  59532. minDist = dist;
  59533. nearestIdx = layerSeries[i].indices[j];
  59534. }
  59535. }
  59536. indices.push(nearestIdx);
  59537. }
  59538. return {dataIndices: indices, nestestValue: nestestValue};
  59539. },
  59540. /**
  59541. * @override
  59542. * @param {number} dataIndex index of data
  59543. */
  59544. formatTooltip: function (dataIndex) {
  59545. var data = this.getData();
  59546. var htmlName = data.getName(dataIndex);
  59547. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  59548. if (isNaN(htmlValue) || htmlValue == null) {
  59549. htmlValue = '-';
  59550. }
  59551. return encodeHTML(htmlName + ' : ' + htmlValue);
  59552. },
  59553. defaultOption: {
  59554. zlevel: 0,
  59555. z: 2,
  59556. coordinateSystem: 'singleAxis',
  59557. // gap in axis's orthogonal orientation
  59558. boundaryGap: ['10%', '10%'],
  59559. // legendHoverLink: true,
  59560. singleAxisIndex: 0,
  59561. animationEasing: 'linear',
  59562. label: {
  59563. margin: 4,
  59564. show: true,
  59565. position: 'left',
  59566. color: '#000',
  59567. fontSize: 11
  59568. },
  59569. emphasis: {
  59570. label: {
  59571. show: true
  59572. }
  59573. }
  59574. }
  59575. });
  59576. /*
  59577. * Licensed to the Apache Software Foundation (ASF) under one
  59578. * or more contributor license agreements. See the NOTICE file
  59579. * distributed with this work for additional information
  59580. * regarding copyright ownership. The ASF licenses this file
  59581. * to you under the Apache License, Version 2.0 (the
  59582. * "License"); you may not use this file except in compliance
  59583. * with the License. You may obtain a copy of the License at
  59584. *
  59585. * http://www.apache.org/licenses/LICENSE-2.0
  59586. *
  59587. * Unless required by applicable law or agreed to in writing,
  59588. * software distributed under the License is distributed on an
  59589. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59590. * KIND, either express or implied. See the License for the
  59591. * specific language governing permissions and limitations
  59592. * under the License.
  59593. */
  59594. /**
  59595. * @file The file used to draw themeRiver view
  59596. * @author Deqing Li(annong035@gmail.com)
  59597. */
  59598. extendChartView({
  59599. type: 'themeRiver',
  59600. init: function () {
  59601. this._layers = [];
  59602. },
  59603. render: function (seriesModel, ecModel, api) {
  59604. var data = seriesModel.getData();
  59605. var group = this.group;
  59606. var layerSeries = seriesModel.getLayerSeries();
  59607. var layoutInfo = data.getLayout('layoutInfo');
  59608. var rect = layoutInfo.rect;
  59609. var boundaryGap = layoutInfo.boundaryGap;
  59610. group.attr('position', [0, rect.y + boundaryGap[0]]);
  59611. function keyGetter(item) {
  59612. return item.name;
  59613. }
  59614. var dataDiffer = new DataDiffer(
  59615. this._layersSeries || [], layerSeries,
  59616. keyGetter, keyGetter
  59617. );
  59618. var newLayersGroups = {};
  59619. dataDiffer
  59620. .add(bind(process, this, 'add'))
  59621. .update(bind(process, this, 'update'))
  59622. .remove(bind(process, this, 'remove'))
  59623. .execute();
  59624. function process(status, idx, oldIdx) {
  59625. var oldLayersGroups = this._layers;
  59626. if (status === 'remove') {
  59627. group.remove(oldLayersGroups[idx]);
  59628. return;
  59629. }
  59630. var points0 = [];
  59631. var points1 = [];
  59632. var color;
  59633. var indices = layerSeries[idx].indices;
  59634. for (var j = 0; j < indices.length; j++) {
  59635. var layout = data.getItemLayout(indices[j]);
  59636. var x = layout.x;
  59637. var y0 = layout.y0;
  59638. var y = layout.y;
  59639. points0.push([x, y0]);
  59640. points1.push([x, y0 + y]);
  59641. color = data.getItemVisual(indices[j], 'color');
  59642. }
  59643. var polygon;
  59644. var text;
  59645. var textLayout = data.getItemLayout(indices[0]);
  59646. var itemModel = data.getItemModel(indices[j - 1]);
  59647. var labelModel = itemModel.getModel('label');
  59648. var margin = labelModel.get('margin');
  59649. if (status === 'add') {
  59650. var layerGroup = newLayersGroups[idx] = new Group();
  59651. polygon = new Polygon$1({
  59652. shape: {
  59653. points: points0,
  59654. stackedOnPoints: points1,
  59655. smooth: 0.4,
  59656. stackedOnSmooth: 0.4,
  59657. smoothConstraint: false
  59658. },
  59659. z2: 0
  59660. });
  59661. text = new Text({
  59662. style: {
  59663. x: textLayout.x - margin,
  59664. y: textLayout.y0 + textLayout.y / 2
  59665. }
  59666. });
  59667. layerGroup.add(polygon);
  59668. layerGroup.add(text);
  59669. group.add(layerGroup);
  59670. polygon.setClipPath(createGridClipShape$3(polygon.getBoundingRect(), seriesModel, function () {
  59671. polygon.removeClipPath();
  59672. }));
  59673. }
  59674. else {
  59675. var layerGroup = oldLayersGroups[oldIdx];
  59676. polygon = layerGroup.childAt(0);
  59677. text = layerGroup.childAt(1);
  59678. group.add(layerGroup);
  59679. newLayersGroups[idx] = layerGroup;
  59680. updateProps(polygon, {
  59681. shape: {
  59682. points: points0,
  59683. stackedOnPoints: points1
  59684. }
  59685. }, seriesModel);
  59686. updateProps(text, {
  59687. style: {
  59688. x: textLayout.x - margin,
  59689. y: textLayout.y0 + textLayout.y / 2
  59690. }
  59691. }, seriesModel);
  59692. }
  59693. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  59694. var itemStyleModel = itemModel.getModel('itemStyle');
  59695. setTextStyle(text.style, labelModel, {
  59696. text: labelModel.get('show')
  59697. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  59698. || data.getName(indices[j - 1])
  59699. : null,
  59700. textVerticalAlign: 'middle'
  59701. });
  59702. polygon.setStyle(extend({
  59703. fill: color
  59704. }, itemStyleModel.getItemStyle(['color'])));
  59705. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  59706. }
  59707. this._layersSeries = layerSeries;
  59708. this._layers = newLayersGroups;
  59709. },
  59710. dispose: function () {}
  59711. });
  59712. // add animation to the view
  59713. function createGridClipShape$3(rect, seriesModel, cb) {
  59714. var rectEl = new Rect({
  59715. shape: {
  59716. x: rect.x - 10,
  59717. y: rect.y - 10,
  59718. width: 0,
  59719. height: rect.height + 20
  59720. }
  59721. });
  59722. initProps(rectEl, {
  59723. shape: {
  59724. width: rect.width + 20,
  59725. height: rect.height + 20
  59726. }
  59727. }, seriesModel, cb);
  59728. return rectEl;
  59729. }
  59730. /*
  59731. * Licensed to the Apache Software Foundation (ASF) under one
  59732. * or more contributor license agreements. See the NOTICE file
  59733. * distributed with this work for additional information
  59734. * regarding copyright ownership. The ASF licenses this file
  59735. * to you under the Apache License, Version 2.0 (the
  59736. * "License"); you may not use this file except in compliance
  59737. * with the License. You may obtain a copy of the License at
  59738. *
  59739. * http://www.apache.org/licenses/LICENSE-2.0
  59740. *
  59741. * Unless required by applicable law or agreed to in writing,
  59742. * software distributed under the License is distributed on an
  59743. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59744. * KIND, either express or implied. See the License for the
  59745. * specific language governing permissions and limitations
  59746. * under the License.
  59747. */
  59748. /**
  59749. * @file Using layout algorithm transform the raw data to layout information.
  59750. * @author Deqing Li(annong035@gmail.com)
  59751. */
  59752. var themeRiverLayout = function (ecModel, api) {
  59753. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  59754. var data = seriesModel.getData();
  59755. var single = seriesModel.coordinateSystem;
  59756. var layoutInfo = {};
  59757. // use the axis boundingRect for view
  59758. var rect = single.getRect();
  59759. layoutInfo.rect = rect;
  59760. var boundaryGap = seriesModel.get('boundaryGap');
  59761. var axis = single.getAxis();
  59762. layoutInfo.boundaryGap = boundaryGap;
  59763. if (axis.orient === 'horizontal') {
  59764. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  59765. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  59766. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  59767. themeRiverLayout$1(data, seriesModel, height);
  59768. }
  59769. else {
  59770. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  59771. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  59772. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  59773. themeRiverLayout$1(data, seriesModel, width);
  59774. }
  59775. data.setLayout('layoutInfo', layoutInfo);
  59776. });
  59777. };
  59778. /**
  59779. * The layout information about themeriver
  59780. *
  59781. * @param {module:echarts/data/List} data data in the series
  59782. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  59783. * @param {number} height value used to compute every series height
  59784. */
  59785. function themeRiverLayout$1(data, seriesModel, height) {
  59786. if (!data.count()) {
  59787. return;
  59788. }
  59789. var coordSys = seriesModel.coordinateSystem;
  59790. // the data in each layer are organized into a series.
  59791. var layerSeries = seriesModel.getLayerSeries();
  59792. // the points in each layer.
  59793. var timeDim = data.mapDimension('single');
  59794. var valueDim = data.mapDimension('value');
  59795. var layerPoints = map(layerSeries, function (singleLayer) {
  59796. return map(singleLayer.indices, function (idx) {
  59797. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  59798. pt[1] = data.get(valueDim, idx);
  59799. return pt;
  59800. });
  59801. });
  59802. var base = computeBaseline(layerPoints);
  59803. var baseLine = base.y0;
  59804. var ky = height / base.max;
  59805. // set layout information for each item.
  59806. var n = layerSeries.length;
  59807. var m = layerSeries[0].indices.length;
  59808. var baseY0;
  59809. for (var j = 0; j < m; ++j) {
  59810. baseY0 = baseLine[j] * ky;
  59811. data.setItemLayout(layerSeries[0].indices[j], {
  59812. layerIndex: 0,
  59813. x: layerPoints[0][j][0],
  59814. y0: baseY0,
  59815. y: layerPoints[0][j][1] * ky
  59816. });
  59817. for (var i = 1; i < n; ++i) {
  59818. baseY0 += layerPoints[i - 1][j][1] * ky;
  59819. data.setItemLayout(layerSeries[i].indices[j], {
  59820. layerIndex: i,
  59821. x: layerPoints[i][j][0],
  59822. y0: baseY0,
  59823. y: layerPoints[i][j][1] * ky
  59824. });
  59825. }
  59826. }
  59827. }
  59828. /**
  59829. * Compute the baseLine of the rawdata
  59830. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  59831. *
  59832. * @param {Array.<Array>} data the points in each layer
  59833. * @return {Object}
  59834. */
  59835. function computeBaseline(data) {
  59836. var layerNum = data.length;
  59837. var pointNum = data[0].length;
  59838. var sums = [];
  59839. var y0 = [];
  59840. var max = 0;
  59841. var temp;
  59842. var base = {};
  59843. for (var i = 0; i < pointNum; ++i) {
  59844. for (var j = 0, temp = 0; j < layerNum; ++j) {
  59845. temp += data[j][i][1];
  59846. }
  59847. if (temp > max) {
  59848. max = temp;
  59849. }
  59850. sums.push(temp);
  59851. }
  59852. for (var k = 0; k < pointNum; ++k) {
  59853. y0[k] = (max - sums[k]) / 2;
  59854. }
  59855. max = 0;
  59856. for (var l = 0; l < pointNum; ++l) {
  59857. var sum = sums[l] + y0[l];
  59858. if (sum > max) {
  59859. max = sum;
  59860. }
  59861. }
  59862. base.y0 = y0;
  59863. base.max = max;
  59864. return base;
  59865. }
  59866. /*
  59867. * Licensed to the Apache Software Foundation (ASF) under one
  59868. * or more contributor license agreements. See the NOTICE file
  59869. * distributed with this work for additional information
  59870. * regarding copyright ownership. The ASF licenses this file
  59871. * to you under the Apache License, Version 2.0 (the
  59872. * "License"); you may not use this file except in compliance
  59873. * with the License. You may obtain a copy of the License at
  59874. *
  59875. * http://www.apache.org/licenses/LICENSE-2.0
  59876. *
  59877. * Unless required by applicable law or agreed to in writing,
  59878. * software distributed under the License is distributed on an
  59879. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59880. * KIND, either express or implied. See the License for the
  59881. * specific language governing permissions and limitations
  59882. * under the License.
  59883. */
  59884. /**
  59885. * @file Visual encoding for themeRiver view
  59886. * @author Deqing Li(annong035@gmail.com)
  59887. */
  59888. var themeRiverVisual = function (ecModel) {
  59889. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  59890. var data = seriesModel.getData();
  59891. var rawData = seriesModel.getRawData();
  59892. var colorList = seriesModel.get('color');
  59893. var idxMap = createHashMap();
  59894. data.each(function (idx) {
  59895. idxMap.set(data.getRawIndex(idx), idx);
  59896. });
  59897. rawData.each(function (rawIndex) {
  59898. var name = rawData.getName(rawIndex);
  59899. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  59900. rawData.setItemVisual(rawIndex, 'color', color);
  59901. var idx = idxMap.get(rawIndex);
  59902. if (idx != null) {
  59903. data.setItemVisual(idx, 'color', color);
  59904. }
  59905. });
  59906. });
  59907. };
  59908. /*
  59909. * Licensed to the Apache Software Foundation (ASF) under one
  59910. * or more contributor license agreements. See the NOTICE file
  59911. * distributed with this work for additional information
  59912. * regarding copyright ownership. The ASF licenses this file
  59913. * to you under the Apache License, Version 2.0 (the
  59914. * "License"); you may not use this file except in compliance
  59915. * with the License. You may obtain a copy of the License at
  59916. *
  59917. * http://www.apache.org/licenses/LICENSE-2.0
  59918. *
  59919. * Unless required by applicable law or agreed to in writing,
  59920. * software distributed under the License is distributed on an
  59921. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59922. * KIND, either express or implied. See the License for the
  59923. * specific language governing permissions and limitations
  59924. * under the License.
  59925. */
  59926. registerLayout(themeRiverLayout);
  59927. registerVisual(themeRiverVisual);
  59928. registerProcessor(dataFilter('themeRiver'));
  59929. /*
  59930. * Licensed to the Apache Software Foundation (ASF) under one
  59931. * or more contributor license agreements. See the NOTICE file
  59932. * distributed with this work for additional information
  59933. * regarding copyright ownership. The ASF licenses this file
  59934. * to you under the Apache License, Version 2.0 (the
  59935. * "License"); you may not use this file except in compliance
  59936. * with the License. You may obtain a copy of the License at
  59937. *
  59938. * http://www.apache.org/licenses/LICENSE-2.0
  59939. *
  59940. * Unless required by applicable law or agreed to in writing,
  59941. * software distributed under the License is distributed on an
  59942. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59943. * KIND, either express or implied. See the License for the
  59944. * specific language governing permissions and limitations
  59945. * under the License.
  59946. */
  59947. SeriesModel.extend({
  59948. type: 'series.sunburst',
  59949. /**
  59950. * @type {module:echarts/data/Tree~Node}
  59951. */
  59952. _viewRoot: null,
  59953. getInitialData: function (option, ecModel) {
  59954. // Create a virtual root.
  59955. var root = { name: option.name, children: option.data };
  59956. completeTreeValue$1(root);
  59957. var levels = option.levels || [];
  59958. // levels = option.levels = setDefault(levels, ecModel);
  59959. var treeOption = {};
  59960. treeOption.levels = levels;
  59961. // Make sure always a new tree is created when setOption,
  59962. // in TreemapView, we check whether oldTree === newTree
  59963. // to choose mappings approach among old shapes and new shapes.
  59964. return Tree.createTree(root, this, treeOption).data;
  59965. },
  59966. optionUpdated: function () {
  59967. this.resetViewRoot();
  59968. },
  59969. /*
  59970. * @override
  59971. */
  59972. getDataParams: function (dataIndex) {
  59973. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  59974. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  59975. params.treePathInfo = wrapTreePathInfo(node, this);
  59976. return params;
  59977. },
  59978. defaultOption: {
  59979. zlevel: 0,
  59980. z: 2,
  59981. // 默认全局居中
  59982. center: ['50%', '50%'],
  59983. radius: [0, '75%'],
  59984. // 默认顺时针
  59985. clockwise: true,
  59986. startAngle: 90,
  59987. // 最小角度改为0
  59988. minAngle: 0,
  59989. percentPrecision: 2,
  59990. // If still show when all data zero.
  59991. stillShowZeroSum: true,
  59992. // Policy of highlighting pieces when hover on one
  59993. // Valid values: 'none' (for not downplay others), 'descendant',
  59994. // 'ancestor', 'self'
  59995. highlightPolicy: 'descendant',
  59996. // 'rootToNode', 'link', or false
  59997. nodeClick: 'rootToNode',
  59998. renderLabelForZeroData: false,
  59999. label: {
  60000. // could be: 'radial', 'tangential', or 'none'
  60001. rotate: 'radial',
  60002. show: true,
  60003. opacity: 1,
  60004. // 'left' is for inner side of inside, and 'right' is for outter
  60005. // side for inside
  60006. align: 'center',
  60007. position: 'inside',
  60008. distance: 5,
  60009. silent: true,
  60010. emphasis: {}
  60011. },
  60012. itemStyle: {
  60013. borderWidth: 1,
  60014. borderColor: 'white',
  60015. borderType: 'solid',
  60016. shadowBlur: 0,
  60017. shadowColor: 'rgba(0, 0, 0, 0.2)',
  60018. shadowOffsetX: 0,
  60019. shadowOffsetY: 0,
  60020. opacity: 1,
  60021. emphasis: {},
  60022. highlight: {
  60023. opacity: 1
  60024. },
  60025. downplay: {
  60026. opacity: 0.9
  60027. }
  60028. },
  60029. // Animation type canbe expansion, scale
  60030. animationType: 'expansion',
  60031. animationDuration: 1000,
  60032. animationDurationUpdate: 500,
  60033. animationEasing: 'cubicOut',
  60034. data: [],
  60035. levels: [],
  60036. /**
  60037. * Sort order.
  60038. *
  60039. * Valid values: 'desc', 'asc', null, or callback function.
  60040. * 'desc' and 'asc' for descend and ascendant order;
  60041. * null for not sorting;
  60042. * example of callback function:
  60043. * function(nodeA, nodeB) {
  60044. * return nodeA.getValue() - nodeB.getValue();
  60045. * }
  60046. */
  60047. sort: 'desc'
  60048. },
  60049. getViewRoot: function () {
  60050. return this._viewRoot;
  60051. },
  60052. /**
  60053. * @param {module:echarts/data/Tree~Node} [viewRoot]
  60054. */
  60055. resetViewRoot: function (viewRoot) {
  60056. viewRoot
  60057. ? (this._viewRoot = viewRoot)
  60058. : (viewRoot = this._viewRoot);
  60059. var root = this.getRawData().tree.root;
  60060. if (!viewRoot
  60061. || (viewRoot !== root && !root.contains(viewRoot))
  60062. ) {
  60063. this._viewRoot = root;
  60064. }
  60065. }
  60066. });
  60067. /**
  60068. * @param {Object} dataNode
  60069. */
  60070. function completeTreeValue$1(dataNode) {
  60071. // Postorder travel tree.
  60072. // If value of none-leaf node is not set,
  60073. // calculate it by suming up the value of all children.
  60074. var sum = 0;
  60075. each$1(dataNode.children, function (child) {
  60076. completeTreeValue$1(child);
  60077. var childValue = child.value;
  60078. isArray(childValue) && (childValue = childValue[0]);
  60079. sum += childValue;
  60080. });
  60081. var thisValue = dataNode.value;
  60082. if (isArray(thisValue)) {
  60083. thisValue = thisValue[0];
  60084. }
  60085. if (thisValue == null || isNaN(thisValue)) {
  60086. thisValue = sum;
  60087. }
  60088. // Value should not less than 0.
  60089. if (thisValue < 0) {
  60090. thisValue = 0;
  60091. }
  60092. isArray(dataNode.value)
  60093. ? (dataNode.value[0] = thisValue)
  60094. : (dataNode.value = thisValue);
  60095. }
  60096. /*
  60097. * Licensed to the Apache Software Foundation (ASF) under one
  60098. * or more contributor license agreements. See the NOTICE file
  60099. * distributed with this work for additional information
  60100. * regarding copyright ownership. The ASF licenses this file
  60101. * to you under the Apache License, Version 2.0 (the
  60102. * "License"); you may not use this file except in compliance
  60103. * with the License. You may obtain a copy of the License at
  60104. *
  60105. * http://www.apache.org/licenses/LICENSE-2.0
  60106. *
  60107. * Unless required by applicable law or agreed to in writing,
  60108. * software distributed under the License is distributed on an
  60109. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60110. * KIND, either express or implied. See the License for the
  60111. * specific language governing permissions and limitations
  60112. * under the License.
  60113. */
  60114. var NodeHighlightPolicy = {
  60115. NONE: 'none', // not downplay others
  60116. DESCENDANT: 'descendant',
  60117. ANCESTOR: 'ancestor',
  60118. SELF: 'self'
  60119. };
  60120. var DEFAULT_SECTOR_Z = 2;
  60121. var DEFAULT_TEXT_Z = 4;
  60122. /**
  60123. * Sunburstce of Sunburst including Sector, Label, LabelLine
  60124. * @constructor
  60125. * @extends {module:zrender/graphic/Group}
  60126. */
  60127. function SunburstPiece(node, seriesModel, ecModel) {
  60128. Group.call(this);
  60129. var sector = new Sector({
  60130. z2: DEFAULT_SECTOR_Z
  60131. });
  60132. sector.seriesIndex = seriesModel.seriesIndex;
  60133. var text = new Text({
  60134. z2: DEFAULT_TEXT_Z,
  60135. silent: node.getModel('label').get('silent')
  60136. });
  60137. this.add(sector);
  60138. this.add(text);
  60139. this.updateData(true, node, 'normal', seriesModel, ecModel);
  60140. // Hover to change label and labelLine
  60141. function onEmphasis() {
  60142. text.ignore = text.hoverIgnore;
  60143. }
  60144. function onNormal() {
  60145. text.ignore = text.normalIgnore;
  60146. }
  60147. this.on('emphasis', onEmphasis)
  60148. .on('normal', onNormal)
  60149. .on('mouseover', onEmphasis)
  60150. .on('mouseout', onNormal);
  60151. }
  60152. var SunburstPieceProto = SunburstPiece.prototype;
  60153. SunburstPieceProto.updateData = function (
  60154. firstCreate,
  60155. node,
  60156. state,
  60157. seriesModel,
  60158. ecModel
  60159. ) {
  60160. this.node = node;
  60161. node.piece = this;
  60162. seriesModel = seriesModel || this._seriesModel;
  60163. ecModel = ecModel || this._ecModel;
  60164. var sector = this.childAt(0);
  60165. sector.dataIndex = node.dataIndex;
  60166. var itemModel = node.getModel();
  60167. var layout = node.getLayout();
  60168. // if (!layout) {
  60169. // console.log(node.getLayout());
  60170. // }
  60171. var sectorShape = extend({}, layout);
  60172. sectorShape.label = null;
  60173. var visualColor = getNodeColor(node, seriesModel, ecModel);
  60174. fillDefaultColor(node, seriesModel, visualColor);
  60175. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  60176. var style;
  60177. if (state === 'normal') {
  60178. style = normalStyle;
  60179. }
  60180. else {
  60181. var stateStyle = itemModel.getModel(state + '.itemStyle')
  60182. .getItemStyle();
  60183. style = merge(stateStyle, normalStyle);
  60184. }
  60185. style = defaults(
  60186. {
  60187. lineJoin: 'bevel',
  60188. fill: style.fill || visualColor
  60189. },
  60190. style
  60191. );
  60192. if (firstCreate) {
  60193. sector.setShape(sectorShape);
  60194. sector.shape.r = layout.r0;
  60195. updateProps(
  60196. sector,
  60197. {
  60198. shape: {
  60199. r: layout.r
  60200. }
  60201. },
  60202. seriesModel,
  60203. node.dataIndex
  60204. );
  60205. sector.useStyle(style);
  60206. }
  60207. else if (typeof style.fill === 'object' && style.fill.type
  60208. || typeof sector.style.fill === 'object' && sector.style.fill.type
  60209. ) {
  60210. // Disable animation for gradient since no interpolation method
  60211. // is supported for gradient
  60212. updateProps(sector, {
  60213. shape: sectorShape
  60214. }, seriesModel);
  60215. sector.useStyle(style);
  60216. }
  60217. else {
  60218. updateProps(sector, {
  60219. shape: sectorShape,
  60220. style: style
  60221. }, seriesModel);
  60222. }
  60223. this._updateLabel(seriesModel, visualColor, state);
  60224. var cursorStyle = itemModel.getShallow('cursor');
  60225. cursorStyle && sector.attr('cursor', cursorStyle);
  60226. if (firstCreate) {
  60227. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  60228. this._initEvents(sector, node, seriesModel, highlightPolicy);
  60229. }
  60230. this._seriesModel = seriesModel || this._seriesModel;
  60231. this._ecModel = ecModel || this._ecModel;
  60232. };
  60233. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  60234. var that = this;
  60235. this.node.hostTree.root.eachNode(function (n) {
  60236. if (n.piece) {
  60237. if (that.node === n) {
  60238. n.piece.updateData(false, n, 'emphasis');
  60239. }
  60240. else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  60241. n.piece.childAt(0).trigger('highlight');
  60242. }
  60243. else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  60244. n.piece.childAt(0).trigger('downplay');
  60245. }
  60246. }
  60247. });
  60248. };
  60249. SunburstPieceProto.onNormal = function () {
  60250. this.node.hostTree.root.eachNode(function (n) {
  60251. if (n.piece) {
  60252. n.piece.updateData(false, n, 'normal');
  60253. }
  60254. });
  60255. };
  60256. SunburstPieceProto.onHighlight = function () {
  60257. this.updateData(false, this.node, 'highlight');
  60258. };
  60259. SunburstPieceProto.onDownplay = function () {
  60260. this.updateData(false, this.node, 'downplay');
  60261. };
  60262. SunburstPieceProto._updateLabel = function (seriesModel, visualColor, state) {
  60263. var itemModel = this.node.getModel();
  60264. var normalModel = itemModel.getModel('label');
  60265. var labelModel = state === 'normal' || state === 'emphasis'
  60266. ? normalModel
  60267. : itemModel.getModel(state + '.label');
  60268. var labelHoverModel = itemModel.getModel('emphasis.label');
  60269. var text = retrieve(
  60270. seriesModel.getFormattedLabel(
  60271. this.node.dataIndex, 'normal', null, null, 'label'
  60272. ),
  60273. this.node.name
  60274. );
  60275. if (getLabelAttr('show') === false) {
  60276. text = '';
  60277. }
  60278. var layout = this.node.getLayout();
  60279. var labelMinAngle = labelModel.get('minAngle');
  60280. if (labelMinAngle == null) {
  60281. labelMinAngle = normalModel.get('minAngle');
  60282. }
  60283. labelMinAngle = labelMinAngle / 180 * Math.PI;
  60284. var angle = layout.endAngle - layout.startAngle;
  60285. if (labelMinAngle != null && Math.abs(angle) < labelMinAngle) {
  60286. // Not displaying text when angle is too small
  60287. text = '';
  60288. }
  60289. var label = this.childAt(1);
  60290. setLabelStyle(
  60291. label.style, label.hoverStyle || {}, normalModel, labelHoverModel,
  60292. {
  60293. defaultText: labelModel.getShallow('show') ? text : null,
  60294. autoColor: visualColor,
  60295. useInsideStyle: true
  60296. }
  60297. );
  60298. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  60299. var dx = Math.cos(midAngle);
  60300. var dy = Math.sin(midAngle);
  60301. var r;
  60302. var labelPosition = getLabelAttr('position');
  60303. var labelPadding = getLabelAttr('distance') || 0;
  60304. var textAlign = getLabelAttr('align');
  60305. if (labelPosition === 'outside') {
  60306. r = layout.r + labelPadding;
  60307. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  60308. }
  60309. else {
  60310. if (!textAlign || textAlign === 'center') {
  60311. r = (layout.r + layout.r0) / 2;
  60312. textAlign = 'center';
  60313. }
  60314. else if (textAlign === 'left') {
  60315. r = layout.r0 + labelPadding;
  60316. if (midAngle > Math.PI / 2) {
  60317. textAlign = 'right';
  60318. }
  60319. }
  60320. else if (textAlign === 'right') {
  60321. r = layout.r - labelPadding;
  60322. if (midAngle > Math.PI / 2) {
  60323. textAlign = 'left';
  60324. }
  60325. }
  60326. }
  60327. label.attr('style', {
  60328. text: text,
  60329. textAlign: textAlign,
  60330. textVerticalAlign: getLabelAttr('verticalAlign') || 'middle',
  60331. opacity: getLabelAttr('opacity')
  60332. });
  60333. var textX = r * dx + layout.cx;
  60334. var textY = r * dy + layout.cy;
  60335. label.attr('position', [textX, textY]);
  60336. var rotateType = getLabelAttr('rotate');
  60337. var rotate = 0;
  60338. if (rotateType === 'radial') {
  60339. rotate = -midAngle;
  60340. if (rotate < -Math.PI / 2) {
  60341. rotate += Math.PI;
  60342. }
  60343. }
  60344. else if (rotateType === 'tangential') {
  60345. rotate = Math.PI / 2 - midAngle;
  60346. if (rotate > Math.PI / 2) {
  60347. rotate -= Math.PI;
  60348. }
  60349. else if (rotate < -Math.PI / 2) {
  60350. rotate += Math.PI;
  60351. }
  60352. } else if (typeof rotateType === 'number') {
  60353. rotate = rotateType * Math.PI / 180;
  60354. }
  60355. label.attr('rotation', rotate);
  60356. function getLabelAttr(name) {
  60357. var stateAttr = labelModel.get(name);
  60358. if (stateAttr == null) {
  60359. return normalModel.get(name);
  60360. }
  60361. else {
  60362. return stateAttr;
  60363. }
  60364. }
  60365. };
  60366. SunburstPieceProto._initEvents = function (
  60367. sector,
  60368. node,
  60369. seriesModel,
  60370. highlightPolicy
  60371. ) {
  60372. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  60373. var that = this;
  60374. var onEmphasis = function () {
  60375. that.onEmphasis(highlightPolicy);
  60376. };
  60377. var onNormal = function () {
  60378. that.onNormal();
  60379. };
  60380. var onDownplay = function () {
  60381. that.onDownplay();
  60382. };
  60383. var onHighlight = function () {
  60384. that.onHighlight();
  60385. };
  60386. if (seriesModel.isAnimationEnabled()) {
  60387. sector
  60388. .on('mouseover', onEmphasis)
  60389. .on('mouseout', onNormal)
  60390. .on('emphasis', onEmphasis)
  60391. .on('normal', onNormal)
  60392. .on('downplay', onDownplay)
  60393. .on('highlight', onHighlight);
  60394. }
  60395. };
  60396. inherits(SunburstPiece, Group);
  60397. /**
  60398. * Get node color
  60399. *
  60400. * @param {TreeNode} node the node to get color
  60401. * @param {module:echarts/model/Series} seriesModel series
  60402. * @param {module:echarts/model/Global} ecModel echarts defaults
  60403. */
  60404. function getNodeColor(node, seriesModel, ecModel) {
  60405. // Color from visualMap
  60406. var visualColor = node.getVisual('color');
  60407. var visualMetaList = node.getVisual('visualMeta');
  60408. if (!visualMetaList || visualMetaList.length === 0) {
  60409. // Use first-generation color if has no visualMap
  60410. visualColor = null;
  60411. }
  60412. // Self color or level color
  60413. var color = node.getModel('itemStyle').get('color');
  60414. if (color) {
  60415. return color;
  60416. }
  60417. else if (visualColor) {
  60418. // Color mapping
  60419. return visualColor;
  60420. }
  60421. else if (node.depth === 0) {
  60422. // Virtual root node
  60423. return ecModel.option.color[0];
  60424. }
  60425. else {
  60426. // First-generation color
  60427. var length = ecModel.option.color.length;
  60428. color = ecModel.option.color[getRootId(node) % length];
  60429. }
  60430. return color;
  60431. }
  60432. /**
  60433. * Get index of root in sorted order
  60434. *
  60435. * @param {TreeNode} node current node
  60436. * @return {number} index in root
  60437. */
  60438. function getRootId(node) {
  60439. var ancestor = node;
  60440. while (ancestor.depth > 1) {
  60441. ancestor = ancestor.parentNode;
  60442. }
  60443. var virtualRoot = node.getAncestors()[0];
  60444. return indexOf(virtualRoot.children, ancestor);
  60445. }
  60446. function isNodeHighlighted(node, activeNode, policy) {
  60447. if (policy === NodeHighlightPolicy.NONE) {
  60448. return false;
  60449. }
  60450. else if (policy === NodeHighlightPolicy.SELF) {
  60451. return node === activeNode;
  60452. }
  60453. else if (policy === NodeHighlightPolicy.ANCESTOR) {
  60454. return node === activeNode || node.isAncestorOf(activeNode);
  60455. }
  60456. else {
  60457. return node === activeNode || node.isDescendantOf(activeNode);
  60458. }
  60459. }
  60460. // Fix tooltip callback function params.color incorrect when pick a default color
  60461. function fillDefaultColor(node, seriesModel, color) {
  60462. var data = seriesModel.getData();
  60463. data.setItemVisual(node.dataIndex, 'color', color);
  60464. }
  60465. /*
  60466. * Licensed to the Apache Software Foundation (ASF) under one
  60467. * or more contributor license agreements. See the NOTICE file
  60468. * distributed with this work for additional information
  60469. * regarding copyright ownership. The ASF licenses this file
  60470. * to you under the Apache License, Version 2.0 (the
  60471. * "License"); you may not use this file except in compliance
  60472. * with the License. You may obtain a copy of the License at
  60473. *
  60474. * http://www.apache.org/licenses/LICENSE-2.0
  60475. *
  60476. * Unless required by applicable law or agreed to in writing,
  60477. * software distributed under the License is distributed on an
  60478. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60479. * KIND, either express or implied. See the License for the
  60480. * specific language governing permissions and limitations
  60481. * under the License.
  60482. */
  60483. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  60484. var SunburstView = Chart.extend({
  60485. type: 'sunburst',
  60486. init: function () {
  60487. },
  60488. render: function (seriesModel, ecModel, api, payload) {
  60489. var that = this;
  60490. this.seriesModel = seriesModel;
  60491. this.api = api;
  60492. this.ecModel = ecModel;
  60493. var data = seriesModel.getData();
  60494. var virtualRoot = data.tree.root;
  60495. var newRoot = seriesModel.getViewRoot();
  60496. var group = this.group;
  60497. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  60498. var newChildren = [];
  60499. newRoot.eachNode(function (node) {
  60500. newChildren.push(node);
  60501. });
  60502. var oldChildren = this._oldChildren || [];
  60503. dualTravel(newChildren, oldChildren);
  60504. renderRollUp(virtualRoot, newRoot);
  60505. if (payload && payload.highlight && payload.highlight.piece) {
  60506. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  60507. payload.highlight.piece.onEmphasis(highlightPolicy);
  60508. }
  60509. else if (payload && payload.unhighlight) {
  60510. var piece = this.virtualPiece;
  60511. if (!piece && virtualRoot.children.length) {
  60512. piece = virtualRoot.children[0].piece;
  60513. }
  60514. if (piece) {
  60515. piece.onNormal();
  60516. }
  60517. }
  60518. this._initEvents();
  60519. this._oldChildren = newChildren;
  60520. function dualTravel(newChildren, oldChildren) {
  60521. if (newChildren.length === 0 && oldChildren.length === 0) {
  60522. return;
  60523. }
  60524. new DataDiffer(oldChildren, newChildren, getKey, getKey)
  60525. .add(processNode)
  60526. .update(processNode)
  60527. .remove(curry(processNode, null))
  60528. .execute();
  60529. function getKey(node) {
  60530. return node.getId();
  60531. }
  60532. function processNode(newId, oldId) {
  60533. var newNode = newId == null ? null : newChildren[newId];
  60534. var oldNode = oldId == null ? null : oldChildren[oldId];
  60535. doRenderNode(newNode, oldNode);
  60536. }
  60537. }
  60538. function doRenderNode(newNode, oldNode) {
  60539. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  60540. // Not render data with value 0
  60541. newNode = null;
  60542. }
  60543. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  60544. if (oldNode && oldNode.piece) {
  60545. if (newNode) {
  60546. // Update
  60547. oldNode.piece.updateData(
  60548. false, newNode, 'normal', seriesModel, ecModel);
  60549. // For tooltip
  60550. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  60551. }
  60552. else {
  60553. // Remove
  60554. removeNode(oldNode);
  60555. }
  60556. }
  60557. else if (newNode) {
  60558. // Add
  60559. var piece = new SunburstPiece(
  60560. newNode,
  60561. seriesModel,
  60562. ecModel
  60563. );
  60564. group.add(piece);
  60565. // For tooltip
  60566. data.setItemGraphicEl(newNode.dataIndex, piece);
  60567. }
  60568. }
  60569. }
  60570. function removeNode(node) {
  60571. if (!node) {
  60572. return;
  60573. }
  60574. if (node.piece) {
  60575. group.remove(node.piece);
  60576. node.piece = null;
  60577. }
  60578. }
  60579. function renderRollUp(virtualRoot, viewRoot) {
  60580. if (viewRoot.depth > 0) {
  60581. // Render
  60582. if (that.virtualPiece) {
  60583. // Update
  60584. that.virtualPiece.updateData(
  60585. false, virtualRoot, 'normal', seriesModel, ecModel);
  60586. }
  60587. else {
  60588. // Add
  60589. that.virtualPiece = new SunburstPiece(
  60590. virtualRoot,
  60591. seriesModel,
  60592. ecModel
  60593. );
  60594. group.add(that.virtualPiece);
  60595. }
  60596. if (viewRoot.piece._onclickEvent) {
  60597. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  60598. }
  60599. var event = function (e) {
  60600. that._rootToNode(viewRoot.parentNode);
  60601. };
  60602. viewRoot.piece._onclickEvent = event;
  60603. that.virtualPiece.on('click', event);
  60604. }
  60605. else if (that.virtualPiece) {
  60606. // Remove
  60607. group.remove(that.virtualPiece);
  60608. that.virtualPiece = null;
  60609. }
  60610. }
  60611. },
  60612. dispose: function () {
  60613. },
  60614. /**
  60615. * @private
  60616. */
  60617. _initEvents: function () {
  60618. var that = this;
  60619. var event = function (e) {
  60620. var targetFound = false;
  60621. var viewRoot = that.seriesModel.getViewRoot();
  60622. viewRoot.eachNode(function (node) {
  60623. if (!targetFound
  60624. && node.piece && node.piece.childAt(0) === e.target
  60625. ) {
  60626. var nodeClick = node.getModel().get('nodeClick');
  60627. if (nodeClick === 'rootToNode') {
  60628. that._rootToNode(node);
  60629. }
  60630. else if (nodeClick === 'link') {
  60631. var itemModel = node.getModel();
  60632. var link = itemModel.get('link');
  60633. if (link) {
  60634. var linkTarget = itemModel.get('target', true)
  60635. || '_blank';
  60636. window.open(link, linkTarget);
  60637. }
  60638. }
  60639. targetFound = true;
  60640. }
  60641. });
  60642. };
  60643. if (this.group._onclickEvent) {
  60644. this.group.off('click', this.group._onclickEvent);
  60645. }
  60646. this.group.on('click', event);
  60647. this.group._onclickEvent = event;
  60648. },
  60649. /**
  60650. * @private
  60651. */
  60652. _rootToNode: function (node) {
  60653. if (node !== this.seriesModel.getViewRoot()) {
  60654. this.api.dispatchAction({
  60655. type: ROOT_TO_NODE_ACTION,
  60656. from: this.uid,
  60657. seriesId: this.seriesModel.id,
  60658. targetNode: node
  60659. });
  60660. }
  60661. },
  60662. /**
  60663. * @implement
  60664. */
  60665. containPoint: function (point, seriesModel) {
  60666. var treeRoot = seriesModel.getData();
  60667. var itemLayout = treeRoot.getItemLayout(0);
  60668. if (itemLayout) {
  60669. var dx = point[0] - itemLayout.cx;
  60670. var dy = point[1] - itemLayout.cy;
  60671. var radius = Math.sqrt(dx * dx + dy * dy);
  60672. return radius <= itemLayout.r && radius >= itemLayout.r0;
  60673. }
  60674. }
  60675. });
  60676. /*
  60677. * Licensed to the Apache Software Foundation (ASF) under one
  60678. * or more contributor license agreements. See the NOTICE file
  60679. * distributed with this work for additional information
  60680. * regarding copyright ownership. The ASF licenses this file
  60681. * to you under the Apache License, Version 2.0 (the
  60682. * "License"); you may not use this file except in compliance
  60683. * with the License. You may obtain a copy of the License at
  60684. *
  60685. * http://www.apache.org/licenses/LICENSE-2.0
  60686. *
  60687. * Unless required by applicable law or agreed to in writing,
  60688. * software distributed under the License is distributed on an
  60689. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60690. * KIND, either express or implied. See the License for the
  60691. * specific language governing permissions and limitations
  60692. * under the License.
  60693. */
  60694. /**
  60695. * @file Sunburst action
  60696. */
  60697. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  60698. registerAction(
  60699. {type: ROOT_TO_NODE_ACTION$1, update: 'updateView'},
  60700. function (payload, ecModel) {
  60701. ecModel.eachComponent(
  60702. {mainType: 'series', subType: 'sunburst', query: payload},
  60703. handleRootToNode
  60704. );
  60705. function handleRootToNode(model, index) {
  60706. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  60707. if (targetInfo) {
  60708. var originViewRoot = model.getViewRoot();
  60709. if (originViewRoot) {
  60710. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  60711. ? 'rollUp' : 'drillDown';
  60712. }
  60713. model.resetViewRoot(targetInfo.node);
  60714. }
  60715. }
  60716. }
  60717. );
  60718. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  60719. registerAction(
  60720. {type: HIGHLIGHT_ACTION, update: 'updateView'},
  60721. function (payload, ecModel) {
  60722. ecModel.eachComponent(
  60723. {mainType: 'series', subType: 'sunburst', query: payload},
  60724. handleHighlight
  60725. );
  60726. function handleHighlight(model, index) {
  60727. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  60728. if (targetInfo) {
  60729. payload.highlight = targetInfo.node;
  60730. }
  60731. }
  60732. }
  60733. );
  60734. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  60735. registerAction(
  60736. {type: UNHIGHLIGHT_ACTION, update: 'updateView'},
  60737. function (payload, ecModel) {
  60738. ecModel.eachComponent(
  60739. {mainType: 'series', subType: 'sunburst', query: payload},
  60740. handleUnhighlight
  60741. );
  60742. function handleUnhighlight(model, index) {
  60743. payload.unhighlight = true;
  60744. }
  60745. }
  60746. );
  60747. /*
  60748. * Licensed to the Apache Software Foundation (ASF) under one
  60749. * or more contributor license agreements. See the NOTICE file
  60750. * distributed with this work for additional information
  60751. * regarding copyright ownership. The ASF licenses this file
  60752. * to you under the Apache License, Version 2.0 (the
  60753. * "License"); you may not use this file except in compliance
  60754. * with the License. You may obtain a copy of the License at
  60755. *
  60756. * http://www.apache.org/licenses/LICENSE-2.0
  60757. *
  60758. * Unless required by applicable law or agreed to in writing,
  60759. * software distributed under the License is distributed on an
  60760. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60761. * KIND, either express or implied. See the License for the
  60762. * specific language governing permissions and limitations
  60763. * under the License.
  60764. */
  60765. var RADIAN$1 = Math.PI / 180;
  60766. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  60767. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  60768. var center = seriesModel.get('center');
  60769. var radius = seriesModel.get('radius');
  60770. if (!isArray(radius)) {
  60771. radius = [0, radius];
  60772. }
  60773. if (!isArray(center)) {
  60774. center = [center, center];
  60775. }
  60776. var width = api.getWidth();
  60777. var height = api.getHeight();
  60778. var size = Math.min(width, height);
  60779. var cx = parsePercent$1(center[0], width);
  60780. var cy = parsePercent$1(center[1], height);
  60781. var r0 = parsePercent$1(radius[0], size / 2);
  60782. var r = parsePercent$1(radius[1], size / 2);
  60783. var startAngle = -seriesModel.get('startAngle') * RADIAN$1;
  60784. var minAngle = seriesModel.get('minAngle') * RADIAN$1;
  60785. var virtualRoot = seriesModel.getData().tree.root;
  60786. var treeRoot = seriesModel.getViewRoot();
  60787. var rootDepth = treeRoot.depth;
  60788. var sort = seriesModel.get('sort');
  60789. if (sort != null) {
  60790. initChildren$1(treeRoot, sort);
  60791. }
  60792. var validDataCount = 0;
  60793. each$1(treeRoot.children, function (child) {
  60794. !isNaN(child.getValue()) && validDataCount++;
  60795. });
  60796. var sum = treeRoot.getValue();
  60797. // Sum may be 0
  60798. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  60799. var renderRollupNode = treeRoot.depth > 0;
  60800. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  60801. var rPerLevel = (r - r0) / (levels || 1);
  60802. var clockwise = seriesModel.get('clockwise');
  60803. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  60804. // In the case some sector angle is smaller than minAngle
  60805. var dir = clockwise ? 1 : -1;
  60806. /**
  60807. * Render a tree
  60808. * @return increased angle
  60809. */
  60810. var renderNode = function (node, startAngle) {
  60811. if (!node) {
  60812. return;
  60813. }
  60814. var endAngle = startAngle;
  60815. // Render self
  60816. if (node !== virtualRoot) {
  60817. // Tree node is virtual, so it doesn't need to be drawn
  60818. var value = node.getValue();
  60819. var angle = (sum === 0 && stillShowZeroSum)
  60820. ? unitRadian : (value * unitRadian);
  60821. if (angle < minAngle) {
  60822. angle = minAngle;
  60823. }
  60824. else {
  60825. }
  60826. endAngle = startAngle + dir * angle;
  60827. var depth = node.depth - rootDepth
  60828. - (renderRollupNode ? -1 : 1);
  60829. var rStart = r0 + rPerLevel * depth;
  60830. var rEnd = r0 + rPerLevel * (depth + 1);
  60831. var itemModel = node.getModel();
  60832. if (itemModel.get('r0') != null) {
  60833. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  60834. }
  60835. if (itemModel.get('r') != null) {
  60836. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  60837. }
  60838. node.setLayout({
  60839. angle: angle,
  60840. startAngle: startAngle,
  60841. endAngle: endAngle,
  60842. clockwise: clockwise,
  60843. cx: cx,
  60844. cy: cy,
  60845. r0: rStart,
  60846. r: rEnd
  60847. });
  60848. }
  60849. // Render children
  60850. if (node.children && node.children.length) {
  60851. // currentAngle = startAngle;
  60852. var siblingAngle = 0;
  60853. each$1(node.children, function (node) {
  60854. siblingAngle += renderNode(node, startAngle + siblingAngle);
  60855. });
  60856. }
  60857. return endAngle - startAngle;
  60858. };
  60859. // Virtual root node for roll up
  60860. if (renderRollupNode) {
  60861. var rStart = r0;
  60862. var rEnd = r0 + rPerLevel;
  60863. var angle = Math.PI * 2;
  60864. virtualRoot.setLayout({
  60865. angle: angle,
  60866. startAngle: startAngle,
  60867. endAngle: startAngle + angle,
  60868. clockwise: clockwise,
  60869. cx: cx,
  60870. cy: cy,
  60871. r0: rStart,
  60872. r: rEnd
  60873. });
  60874. }
  60875. renderNode(treeRoot, startAngle);
  60876. });
  60877. };
  60878. /**
  60879. * Init node children by order and update visual
  60880. *
  60881. * @param {TreeNode} node root node
  60882. * @param {boolean} isAsc if is in ascendant order
  60883. */
  60884. function initChildren$1(node, isAsc) {
  60885. var children = node.children || [];
  60886. node.children = sort$2(children, isAsc);
  60887. // Init children recursively
  60888. if (children.length) {
  60889. each$1(node.children, function (child) {
  60890. initChildren$1(child, isAsc);
  60891. });
  60892. }
  60893. }
  60894. /**
  60895. * Sort children nodes
  60896. *
  60897. * @param {TreeNode[]} children children of node to be sorted
  60898. * @param {string | function | null} sort sort method
  60899. * See SunburstSeries.js for details.
  60900. */
  60901. function sort$2(children, sortOrder) {
  60902. if (typeof sortOrder === 'function') {
  60903. return children.sort(sortOrder);
  60904. }
  60905. else {
  60906. var isAsc = sortOrder === 'asc';
  60907. return children.sort(function (a, b) {
  60908. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  60909. return diff === 0
  60910. ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
  60911. : diff;
  60912. });
  60913. }
  60914. }
  60915. /*
  60916. * Licensed to the Apache Software Foundation (ASF) under one
  60917. * or more contributor license agreements. See the NOTICE file
  60918. * distributed with this work for additional information
  60919. * regarding copyright ownership. The ASF licenses this file
  60920. * to you under the Apache License, Version 2.0 (the
  60921. * "License"); you may not use this file except in compliance
  60922. * with the License. You may obtain a copy of the License at
  60923. *
  60924. * http://www.apache.org/licenses/LICENSE-2.0
  60925. *
  60926. * Unless required by applicable law or agreed to in writing,
  60927. * software distributed under the License is distributed on an
  60928. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60929. * KIND, either express or implied. See the License for the
  60930. * specific language governing permissions and limitations
  60931. * under the License.
  60932. */
  60933. registerVisual(curry(dataColor, 'sunburst'));
  60934. registerLayout(curry(sunburstLayout, 'sunburst'));
  60935. registerProcessor(curry(dataFilter, 'sunburst'));
  60936. /*
  60937. * Licensed to the Apache Software Foundation (ASF) under one
  60938. * or more contributor license agreements. See the NOTICE file
  60939. * distributed with this work for additional information
  60940. * regarding copyright ownership. The ASF licenses this file
  60941. * to you under the Apache License, Version 2.0 (the
  60942. * "License"); you may not use this file except in compliance
  60943. * with the License. You may obtain a copy of the License at
  60944. *
  60945. * http://www.apache.org/licenses/LICENSE-2.0
  60946. *
  60947. * Unless required by applicable law or agreed to in writing,
  60948. * software distributed under the License is distributed on an
  60949. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60950. * KIND, either express or implied. See the License for the
  60951. * specific language governing permissions and limitations
  60952. * under the License.
  60953. */
  60954. function dataToCoordSize(dataSize, dataItem) {
  60955. // dataItem is necessary in log axis.
  60956. dataItem = dataItem || [0, 0];
  60957. return map(['x', 'y'], function (dim, dimIdx) {
  60958. var axis = this.getAxis(dim);
  60959. var val = dataItem[dimIdx];
  60960. var halfSize = dataSize[dimIdx] / 2;
  60961. return axis.type === 'category'
  60962. ? axis.getBandWidth()
  60963. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  60964. }, this);
  60965. }
  60966. var prepareCartesian2d = function (coordSys) {
  60967. var rect = coordSys.grid.getRect();
  60968. return {
  60969. coordSys: {
  60970. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  60971. type: 'cartesian2d',
  60972. x: rect.x,
  60973. y: rect.y,
  60974. width: rect.width,
  60975. height: rect.height
  60976. },
  60977. api: {
  60978. coord: function (data) {
  60979. // do not provide "out" param
  60980. return coordSys.dataToPoint(data);
  60981. },
  60982. size: bind(dataToCoordSize, coordSys)
  60983. }
  60984. };
  60985. };
  60986. /*
  60987. * Licensed to the Apache Software Foundation (ASF) under one
  60988. * or more contributor license agreements. See the NOTICE file
  60989. * distributed with this work for additional information
  60990. * regarding copyright ownership. The ASF licenses this file
  60991. * to you under the Apache License, Version 2.0 (the
  60992. * "License"); you may not use this file except in compliance
  60993. * with the License. You may obtain a copy of the License at
  60994. *
  60995. * http://www.apache.org/licenses/LICENSE-2.0
  60996. *
  60997. * Unless required by applicable law or agreed to in writing,
  60998. * software distributed under the License is distributed on an
  60999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61000. * KIND, either express or implied. See the License for the
  61001. * specific language governing permissions and limitations
  61002. * under the License.
  61003. */
  61004. function dataToCoordSize$1(dataSize, dataItem) {
  61005. dataItem = dataItem || [0, 0];
  61006. return map([0, 1], function (dimIdx) {
  61007. var val = dataItem[dimIdx];
  61008. var halfSize = dataSize[dimIdx] / 2;
  61009. var p1 = [];
  61010. var p2 = [];
  61011. p1[dimIdx] = val - halfSize;
  61012. p2[dimIdx] = val + halfSize;
  61013. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  61014. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  61015. }, this);
  61016. }
  61017. var prepareGeo = function (coordSys) {
  61018. var rect = coordSys.getBoundingRect();
  61019. return {
  61020. coordSys: {
  61021. type: 'geo',
  61022. x: rect.x,
  61023. y: rect.y,
  61024. width: rect.width,
  61025. height: rect.height,
  61026. zoom: coordSys.getZoom()
  61027. },
  61028. api: {
  61029. coord: function (data) {
  61030. // do not provide "out" and noRoam param,
  61031. // Compatible with this usage:
  61032. // echarts.util.map(item.points, api.coord)
  61033. return coordSys.dataToPoint(data);
  61034. },
  61035. size: bind(dataToCoordSize$1, coordSys)
  61036. }
  61037. };
  61038. };
  61039. /*
  61040. * Licensed to the Apache Software Foundation (ASF) under one
  61041. * or more contributor license agreements. See the NOTICE file
  61042. * distributed with this work for additional information
  61043. * regarding copyright ownership. The ASF licenses this file
  61044. * to you under the Apache License, Version 2.0 (the
  61045. * "License"); you may not use this file except in compliance
  61046. * with the License. You may obtain a copy of the License at
  61047. *
  61048. * http://www.apache.org/licenses/LICENSE-2.0
  61049. *
  61050. * Unless required by applicable law or agreed to in writing,
  61051. * software distributed under the License is distributed on an
  61052. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61053. * KIND, either express or implied. See the License for the
  61054. * specific language governing permissions and limitations
  61055. * under the License.
  61056. */
  61057. function dataToCoordSize$2(dataSize, dataItem) {
  61058. // dataItem is necessary in log axis.
  61059. var axis = this.getAxis();
  61060. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  61061. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  61062. return axis.type === 'category'
  61063. ? axis.getBandWidth()
  61064. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  61065. }
  61066. var prepareSingleAxis = function (coordSys) {
  61067. var rect = coordSys.getRect();
  61068. return {
  61069. coordSys: {
  61070. type: 'singleAxis',
  61071. x: rect.x,
  61072. y: rect.y,
  61073. width: rect.width,
  61074. height: rect.height
  61075. },
  61076. api: {
  61077. coord: function (val) {
  61078. // do not provide "out" param
  61079. return coordSys.dataToPoint(val);
  61080. },
  61081. size: bind(dataToCoordSize$2, coordSys)
  61082. }
  61083. };
  61084. };
  61085. /*
  61086. * Licensed to the Apache Software Foundation (ASF) under one
  61087. * or more contributor license agreements. See the NOTICE file
  61088. * distributed with this work for additional information
  61089. * regarding copyright ownership. The ASF licenses this file
  61090. * to you under the Apache License, Version 2.0 (the
  61091. * "License"); you may not use this file except in compliance
  61092. * with the License. You may obtain a copy of the License at
  61093. *
  61094. * http://www.apache.org/licenses/LICENSE-2.0
  61095. *
  61096. * Unless required by applicable law or agreed to in writing,
  61097. * software distributed under the License is distributed on an
  61098. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61099. * KIND, either express or implied. See the License for the
  61100. * specific language governing permissions and limitations
  61101. * under the License.
  61102. */
  61103. function dataToCoordSize$3(dataSize, dataItem) {
  61104. // dataItem is necessary in log axis.
  61105. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  61106. var axis = this['get' + dim + 'Axis']();
  61107. var val = dataItem[dimIdx];
  61108. var halfSize = dataSize[dimIdx] / 2;
  61109. var method = 'dataTo' + dim;
  61110. var result = axis.type === 'category'
  61111. ? axis.getBandWidth()
  61112. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  61113. if (dim === 'Angle') {
  61114. result = result * Math.PI / 180;
  61115. }
  61116. return result;
  61117. }, this);
  61118. }
  61119. var preparePolar = function (coordSys) {
  61120. var radiusAxis = coordSys.getRadiusAxis();
  61121. var angleAxis = coordSys.getAngleAxis();
  61122. var radius = radiusAxis.getExtent();
  61123. radius[0] > radius[1] && radius.reverse();
  61124. return {
  61125. coordSys: {
  61126. type: 'polar',
  61127. cx: coordSys.cx,
  61128. cy: coordSys.cy,
  61129. r: radius[1],
  61130. r0: radius[0]
  61131. },
  61132. api: {
  61133. coord: bind(function (data) {
  61134. var radius = radiusAxis.dataToRadius(data[0]);
  61135. var angle = angleAxis.dataToAngle(data[1]);
  61136. var coord = coordSys.coordToPoint([radius, angle]);
  61137. coord.push(radius, angle * Math.PI / 180);
  61138. return coord;
  61139. }),
  61140. size: bind(dataToCoordSize$3, coordSys)
  61141. }
  61142. };
  61143. };
  61144. /*
  61145. * Licensed to the Apache Software Foundation (ASF) under one
  61146. * or more contributor license agreements. See the NOTICE file
  61147. * distributed with this work for additional information
  61148. * regarding copyright ownership. The ASF licenses this file
  61149. * to you under the Apache License, Version 2.0 (the
  61150. * "License"); you may not use this file except in compliance
  61151. * with the License. You may obtain a copy of the License at
  61152. *
  61153. * http://www.apache.org/licenses/LICENSE-2.0
  61154. *
  61155. * Unless required by applicable law or agreed to in writing,
  61156. * software distributed under the License is distributed on an
  61157. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61158. * KIND, either express or implied. See the License for the
  61159. * specific language governing permissions and limitations
  61160. * under the License.
  61161. */
  61162. var prepareCalendar = function (coordSys) {
  61163. var rect = coordSys.getRect();
  61164. var rangeInfo = coordSys.getRangeInfo();
  61165. return {
  61166. coordSys: {
  61167. type: 'calendar',
  61168. x: rect.x,
  61169. y: rect.y,
  61170. width: rect.width,
  61171. height: rect.height,
  61172. cellWidth: coordSys.getCellWidth(),
  61173. cellHeight: coordSys.getCellHeight(),
  61174. rangeInfo: {
  61175. start: rangeInfo.start,
  61176. end: rangeInfo.end,
  61177. weeks: rangeInfo.weeks,
  61178. dayCount: rangeInfo.allDay
  61179. }
  61180. },
  61181. api: {
  61182. coord: function (data, clamp) {
  61183. return coordSys.dataToPoint(data, clamp);
  61184. }
  61185. }
  61186. };
  61187. };
  61188. /*
  61189. * Licensed to the Apache Software Foundation (ASF) under one
  61190. * or more contributor license agreements. See the NOTICE file
  61191. * distributed with this work for additional information
  61192. * regarding copyright ownership. The ASF licenses this file
  61193. * to you under the Apache License, Version 2.0 (the
  61194. * "License"); you may not use this file except in compliance
  61195. * with the License. You may obtain a copy of the License at
  61196. *
  61197. * http://www.apache.org/licenses/LICENSE-2.0
  61198. *
  61199. * Unless required by applicable law or agreed to in writing,
  61200. * software distributed under the License is distributed on an
  61201. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61202. * KIND, either express or implied. See the License for the
  61203. * specific language governing permissions and limitations
  61204. * under the License.
  61205. */
  61206. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  61207. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  61208. var LABEL_NORMAL = ['label'];
  61209. var LABEL_EMPHASIS = ['emphasis', 'label'];
  61210. // Use prefix to avoid index to be the same as el.name,
  61211. // which will cause weird udpate animation.
  61212. var GROUP_DIFF_PREFIX = 'e\0\0';
  61213. /**
  61214. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  61215. * of each coordinate systems are not required by each coordinate systems directly, but
  61216. * required by the module `custom`.
  61217. *
  61218. * prepareInfoForCustomSeries {Function}: optional
  61219. * @return {Object} {coordSys: {...}, api: {
  61220. * coord: function (data, clamp) {}, // return point in global.
  61221. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  61222. * }}
  61223. */
  61224. var prepareCustoms = {
  61225. cartesian2d: prepareCartesian2d,
  61226. geo: prepareGeo,
  61227. singleAxis: prepareSingleAxis,
  61228. polar: preparePolar,
  61229. calendar: prepareCalendar
  61230. };
  61231. // ------
  61232. // Model
  61233. // ------
  61234. SeriesModel.extend({
  61235. type: 'series.custom',
  61236. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  61237. defaultOption: {
  61238. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  61239. zlevel: 0,
  61240. z: 2,
  61241. legendHoverLink: true,
  61242. useTransform: true
  61243. // Cartesian coordinate system
  61244. // xAxisIndex: 0,
  61245. // yAxisIndex: 0,
  61246. // Polar coordinate system
  61247. // polarIndex: 0,
  61248. // Geo coordinate system
  61249. // geoIndex: 0,
  61250. // label: {}
  61251. // itemStyle: {}
  61252. },
  61253. /**
  61254. * @override
  61255. */
  61256. getInitialData: function (option, ecModel) {
  61257. return createListFromArray(this.getSource(), this);
  61258. },
  61259. /**
  61260. * @override
  61261. */
  61262. getDataParams: function (dataIndex, dataType, el) {
  61263. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  61264. el && (params.info = el.info);
  61265. return params;
  61266. }
  61267. });
  61268. // -----
  61269. // View
  61270. // -----
  61271. Chart.extend({
  61272. type: 'custom',
  61273. /**
  61274. * @private
  61275. * @type {module:echarts/data/List}
  61276. */
  61277. _data: null,
  61278. /**
  61279. * @override
  61280. */
  61281. render: function (customSeries, ecModel, api, payload) {
  61282. var oldData = this._data;
  61283. var data = customSeries.getData();
  61284. var group = this.group;
  61285. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  61286. // By default, merge mode is applied. In most cases, custom series is
  61287. // used in the scenario that data amount is not large but graphic elements
  61288. // is complicated, where merge mode is probably necessary for optimization.
  61289. // For example, reuse graphic elements and only update the transform when
  61290. // roam or data zoom according to `actionType`.
  61291. data.diff(oldData)
  61292. .add(function (newIdx) {
  61293. createOrUpdate$1(
  61294. null, newIdx, renderItem(newIdx, payload), customSeries, group, data
  61295. );
  61296. })
  61297. .update(function (newIdx, oldIdx) {
  61298. var el = oldData.getItemGraphicEl(oldIdx);
  61299. createOrUpdate$1(
  61300. el, newIdx, renderItem(newIdx, payload), customSeries, group, data
  61301. );
  61302. })
  61303. .remove(function (oldIdx) {
  61304. var el = oldData.getItemGraphicEl(oldIdx);
  61305. el && group.remove(el);
  61306. })
  61307. .execute();
  61308. this._data = data;
  61309. },
  61310. incrementalPrepareRender: function (customSeries, ecModel, api) {
  61311. this.group.removeAll();
  61312. this._data = null;
  61313. },
  61314. incrementalRender: function (params, customSeries, ecModel, api, payload) {
  61315. var data = customSeries.getData();
  61316. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  61317. function setIncrementalAndHoverLayer(el) {
  61318. if (!el.isGroup) {
  61319. el.incremental = true;
  61320. el.useHoverLayer = true;
  61321. }
  61322. }
  61323. for (var idx = params.start; idx < params.end; idx++) {
  61324. var el = createOrUpdate$1(null, idx, renderItem(idx, payload), customSeries, this.group, data);
  61325. el.traverse(setIncrementalAndHoverLayer);
  61326. }
  61327. },
  61328. /**
  61329. * @override
  61330. */
  61331. dispose: noop,
  61332. /**
  61333. * @override
  61334. */
  61335. filterForExposedEvent: function (eventType, query, targetEl, packedEvent) {
  61336. var elementName = query.element;
  61337. if (elementName == null || targetEl.name === elementName) {
  61338. return true;
  61339. }
  61340. // Enable to give a name on a group made by `renderItem`, and listen
  61341. // events that triggerd by its descendents.
  61342. while ((targetEl = targetEl.parent) && targetEl !== this.group) {
  61343. if (targetEl.name === elementName) {
  61344. return true;
  61345. }
  61346. }
  61347. return false;
  61348. }
  61349. });
  61350. function createEl(elOption) {
  61351. var graphicType = elOption.type;
  61352. var el;
  61353. if (graphicType === 'path') {
  61354. var shape = elOption.shape;
  61355. // Using pathRect brings convenience to users sacle svg path.
  61356. var pathRect = (shape.width != null && shape.height != null)
  61357. ? {
  61358. x: shape.x || 0,
  61359. y: shape.y || 0,
  61360. width: shape.width,
  61361. height: shape.height
  61362. }
  61363. : null;
  61364. var pathData = getPathData(shape);
  61365. // Path is also used for icon, so layout 'center' by default.
  61366. el = makePath(pathData, null, pathRect, shape.layout || 'center');
  61367. el.__customPathData = pathData;
  61368. }
  61369. else if (graphicType === 'image') {
  61370. el = new ZImage({});
  61371. el.__customImagePath = elOption.style.image;
  61372. }
  61373. else if (graphicType === 'text') {
  61374. el = new Text({});
  61375. el.__customText = elOption.style.text;
  61376. }
  61377. else {
  61378. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  61379. if (__DEV__) {
  61380. assert$1(Clz, 'graphic type "' + graphicType + '" can not be found.');
  61381. }
  61382. el = new Clz();
  61383. }
  61384. el.__customGraphicType = graphicType;
  61385. el.name = elOption.name;
  61386. return el;
  61387. }
  61388. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot) {
  61389. var transitionProps = {};
  61390. var elOptionStyle = elOption.style || {};
  61391. elOption.shape && (transitionProps.shape = clone(elOption.shape));
  61392. elOption.position && (transitionProps.position = elOption.position.slice());
  61393. elOption.scale && (transitionProps.scale = elOption.scale.slice());
  61394. elOption.origin && (transitionProps.origin = elOption.origin.slice());
  61395. elOption.rotation && (transitionProps.rotation = elOption.rotation);
  61396. if (el.type === 'image' && elOption.style) {
  61397. var targetStyle = transitionProps.style = {};
  61398. each$1(['x', 'y', 'width', 'height'], function (prop) {
  61399. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  61400. });
  61401. }
  61402. if (el.type === 'text' && elOption.style) {
  61403. var targetStyle = transitionProps.style = {};
  61404. each$1(['x', 'y'], function (prop) {
  61405. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  61406. });
  61407. // Compatible with previous: both support
  61408. // textFill and fill, textStroke and stroke in 'text' element.
  61409. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  61410. elOptionStyle.textFill = elOptionStyle.fill
  61411. );
  61412. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  61413. elOptionStyle.textStroke = elOptionStyle.stroke
  61414. );
  61415. }
  61416. if (el.type !== 'group') {
  61417. el.useStyle(elOptionStyle);
  61418. // Init animation.
  61419. if (isInit) {
  61420. el.style.opacity = 0;
  61421. var targetOpacity = elOptionStyle.opacity;
  61422. targetOpacity == null && (targetOpacity = 1);
  61423. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  61424. }
  61425. }
  61426. if (isInit) {
  61427. el.attr(transitionProps);
  61428. }
  61429. else {
  61430. updateProps(el, transitionProps, animatableModel, dataIndex);
  61431. }
  61432. // Merge by default.
  61433. // z2 must not be null/undefined, otherwise sort error may occur.
  61434. elOption.hasOwnProperty('z2') && el.attr('z2', elOption.z2 || 0);
  61435. elOption.hasOwnProperty('silent') && el.attr('silent', elOption.silent);
  61436. elOption.hasOwnProperty('invisible') && el.attr('invisible', elOption.invisible);
  61437. elOption.hasOwnProperty('ignore') && el.attr('ignore', elOption.ignore);
  61438. // `elOption.info` enables user to mount some info on
  61439. // elements and use them in event handlers.
  61440. // Update them only when user specified, otherwise, remain.
  61441. elOption.hasOwnProperty('info') && el.attr('info', elOption.info);
  61442. // If `elOption.styleEmphasis` is `false`, remove hover style. The
  61443. // logic is ensured by `graphicUtil.setElementHoverStyle`.
  61444. var styleEmphasis = elOption.styleEmphasis;
  61445. var disableStyleEmphasis = styleEmphasis === false;
  61446. if (!(
  61447. // Try to escapse setting hover style for performance.
  61448. (el.__cusHasEmphStl && styleEmphasis == null)
  61449. || (!el.__cusHasEmphStl && disableStyleEmphasis)
  61450. )) {
  61451. // Should not use graphicUtil.setHoverStyle, since the styleEmphasis
  61452. // should not be share by group and its descendants.
  61453. setElementHoverStyle(el, styleEmphasis);
  61454. el.__cusHasEmphStl = !disableStyleEmphasis;
  61455. }
  61456. isRoot && setAsHoverStyleTrigger(el, !disableStyleEmphasis);
  61457. }
  61458. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  61459. if (elOptionStyle[prop] != null && !isInit) {
  61460. targetStyle[prop] = elOptionStyle[prop];
  61461. elOptionStyle[prop] = oldElStyle[prop];
  61462. }
  61463. }
  61464. function makeRenderItem(customSeries, data, ecModel, api) {
  61465. var renderItem = customSeries.get('renderItem');
  61466. var coordSys = customSeries.coordinateSystem;
  61467. var prepareResult = {};
  61468. if (coordSys) {
  61469. if (__DEV__) {
  61470. assert$1(renderItem, 'series.render is required.');
  61471. assert$1(
  61472. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  61473. 'This coordSys does not support custom series.'
  61474. );
  61475. }
  61476. prepareResult = coordSys.prepareCustoms
  61477. ? coordSys.prepareCustoms()
  61478. : prepareCustoms[coordSys.type](coordSys);
  61479. }
  61480. var userAPI = defaults({
  61481. getWidth: api.getWidth,
  61482. getHeight: api.getHeight,
  61483. getZr: api.getZr,
  61484. getDevicePixelRatio: api.getDevicePixelRatio,
  61485. value: value,
  61486. style: style,
  61487. styleEmphasis: styleEmphasis,
  61488. visual: visual,
  61489. barLayout: barLayout,
  61490. currentSeriesIndices: currentSeriesIndices,
  61491. font: font
  61492. }, prepareResult.api || {});
  61493. var userParams = {
  61494. // The life cycle of context: current round of rendering.
  61495. // The global life cycle is probably not necessary, because
  61496. // user can store global status by themselves.
  61497. context: {},
  61498. seriesId: customSeries.id,
  61499. seriesName: customSeries.name,
  61500. seriesIndex: customSeries.seriesIndex,
  61501. coordSys: prepareResult.coordSys,
  61502. dataInsideLength: data.count(),
  61503. encode: wrapEncodeDef(customSeries.getData())
  61504. };
  61505. // Do not support call `api` asynchronously without dataIndexInside input.
  61506. var currDataIndexInside;
  61507. var currDirty = true;
  61508. var currItemModel;
  61509. var currLabelNormalModel;
  61510. var currLabelEmphasisModel;
  61511. var currVisualColor;
  61512. return function (dataIndexInside, payload) {
  61513. currDataIndexInside = dataIndexInside;
  61514. currDirty = true;
  61515. return renderItem && renderItem(
  61516. defaults({
  61517. dataIndexInside: dataIndexInside,
  61518. dataIndex: data.getRawIndex(dataIndexInside),
  61519. // Can be used for optimization when zoom or roam.
  61520. actionType: payload ? payload.type : null
  61521. }, userParams),
  61522. userAPI
  61523. );
  61524. };
  61525. // Do not update cache until api called.
  61526. function updateCache(dataIndexInside) {
  61527. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61528. if (currDirty) {
  61529. currItemModel = data.getItemModel(dataIndexInside);
  61530. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  61531. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  61532. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  61533. currDirty = false;
  61534. }
  61535. }
  61536. /**
  61537. * @public
  61538. * @param {number|string} dim
  61539. * @param {number} [dataIndexInside=currDataIndexInside]
  61540. * @return {number|string} value
  61541. */
  61542. function value(dim, dataIndexInside) {
  61543. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61544. return data.get(data.getDimension(dim || 0), dataIndexInside);
  61545. }
  61546. /**
  61547. * By default, `visual` is applied to style (to support visualMap).
  61548. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  61549. * it can be implemented as:
  61550. * `api.style({stroke: api.visual('color'), fill: null})`;
  61551. * @public
  61552. * @param {Object} [extra]
  61553. * @param {number} [dataIndexInside=currDataIndexInside]
  61554. */
  61555. function style(extra, dataIndexInside) {
  61556. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61557. updateCache(dataIndexInside);
  61558. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  61559. currVisualColor != null && (itemStyle.fill = currVisualColor);
  61560. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  61561. opacity != null && (itemStyle.opacity = opacity);
  61562. setTextStyle(itemStyle, currLabelNormalModel, null, {
  61563. autoColor: currVisualColor,
  61564. isRectText: true
  61565. });
  61566. itemStyle.text = currLabelNormalModel.getShallow('show')
  61567. ? retrieve2(
  61568. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  61569. getDefaultLabel(data, dataIndexInside)
  61570. )
  61571. : null;
  61572. extra && extend(itemStyle, extra);
  61573. return itemStyle;
  61574. }
  61575. /**
  61576. * @public
  61577. * @param {Object} [extra]
  61578. * @param {number} [dataIndexInside=currDataIndexInside]
  61579. */
  61580. function styleEmphasis(extra, dataIndexInside) {
  61581. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61582. updateCache(dataIndexInside);
  61583. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  61584. setTextStyle(itemStyle, currLabelEmphasisModel, null, {
  61585. isRectText: true
  61586. }, true);
  61587. itemStyle.text = currLabelEmphasisModel.getShallow('show')
  61588. ? retrieve3(
  61589. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  61590. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  61591. getDefaultLabel(data, dataIndexInside)
  61592. )
  61593. : null;
  61594. extra && extend(itemStyle, extra);
  61595. return itemStyle;
  61596. }
  61597. /**
  61598. * @public
  61599. * @param {string} visualType
  61600. * @param {number} [dataIndexInside=currDataIndexInside]
  61601. */
  61602. function visual(visualType, dataIndexInside) {
  61603. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61604. return data.getItemVisual(dataIndexInside, visualType);
  61605. }
  61606. /**
  61607. * @public
  61608. * @param {number} opt.count Positive interger.
  61609. * @param {number} [opt.barWidth]
  61610. * @param {number} [opt.barMaxWidth]
  61611. * @param {number} [opt.barGap]
  61612. * @param {number} [opt.barCategoryGap]
  61613. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  61614. */
  61615. function barLayout(opt) {
  61616. if (coordSys.getBaseAxis) {
  61617. var baseAxis = coordSys.getBaseAxis();
  61618. return getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  61619. }
  61620. }
  61621. /**
  61622. * @public
  61623. * @return {Array.<number>}
  61624. */
  61625. function currentSeriesIndices() {
  61626. return ecModel.getCurrentSeriesIndices();
  61627. }
  61628. /**
  61629. * @public
  61630. * @param {Object} opt
  61631. * @param {string} [opt.fontStyle]
  61632. * @param {number} [opt.fontWeight]
  61633. * @param {number} [opt.fontSize]
  61634. * @param {string} [opt.fontFamily]
  61635. * @return {string} font string
  61636. */
  61637. function font(opt) {
  61638. return getFont(opt, ecModel);
  61639. }
  61640. }
  61641. function wrapEncodeDef(data) {
  61642. var encodeDef = {};
  61643. each$1(data.dimensions, function (dimName, dataDimIndex) {
  61644. var dimInfo = data.getDimensionInfo(dimName);
  61645. if (!dimInfo.isExtraCoord) {
  61646. var coordDim = dimInfo.coordDim;
  61647. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  61648. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  61649. }
  61650. });
  61651. return encodeDef;
  61652. }
  61653. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  61654. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, true);
  61655. el && data.setItemGraphicEl(dataIndex, el);
  61656. return el;
  61657. }
  61658. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, isRoot) {
  61659. // [Rule]
  61660. // By default, follow merge mode.
  61661. // (It probably brings benifit for performance in some cases of large data, where
  61662. // user program can be optimized to that only updated props needed to be re-calculated,
  61663. // or according to `actionType` some calculation can be skipped.)
  61664. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  61665. // (It seems that violate the "merge" principle, but most of users probably intuitively
  61666. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  61667. // most cases.)
  61668. var simplyRemove = !elOption; // `null`/`undefined`/`false`
  61669. elOption = elOption || {};
  61670. var elOptionType = elOption.type;
  61671. var elOptionShape = elOption.shape;
  61672. var elOptionStyle = elOption.style;
  61673. if (el && (
  61674. simplyRemove
  61675. // || elOption.$merge === false
  61676. // If `elOptionType` is `null`, follow the merge principle.
  61677. || (elOptionType != null
  61678. && elOptionType !== el.__customGraphicType
  61679. )
  61680. || (elOptionType === 'path'
  61681. && hasOwnPathData(elOptionShape) && getPathData(elOptionShape) !== el.__customPathData
  61682. )
  61683. || (elOptionType === 'image'
  61684. && hasOwn(elOptionStyle, 'image') && elOptionStyle.image !== el.__customImagePath
  61685. )
  61686. // FIXME test and remove this restriction?
  61687. || (elOptionType === 'text'
  61688. && hasOwn(elOptionShape, 'text') && elOptionStyle.text !== el.__customText
  61689. )
  61690. )) {
  61691. group.remove(el);
  61692. el = null;
  61693. }
  61694. // `elOption.type` is undefined when `renderItem` returns nothing.
  61695. if (simplyRemove) {
  61696. return;
  61697. }
  61698. var isInit = !el;
  61699. !el && (el = createEl(elOption));
  61700. updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot);
  61701. if (elOptionType === 'group') {
  61702. mergeChildren(el, dataIndex, elOption, animatableModel, data);
  61703. }
  61704. // Always add whatever already added to ensure sequence.
  61705. group.add(el);
  61706. return el;
  61707. }
  61708. // Usage:
  61709. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates that
  61710. // the existing children will not be removed, and enables the feature that
  61711. // update some of the props of some of the children simply by construct
  61712. // the returned children of `renderItem` like:
  61713. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  61714. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  61715. // by child.name. But that might be lower performance.
  61716. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  61717. // replaced totally.
  61718. // (4) If `!elOption.children`, following the "merge" principle, nothing will happen.
  61719. //
  61720. // For implementation simpleness, do not provide a direct way to remove sinlge
  61721. // child (otherwise the total indicies of the children array have to be modified).
  61722. // User can remove a single child by set its `ignore` as `true` or replace
  61723. // it by another element, where its `$merge` can be set as `true` if necessary.
  61724. function mergeChildren(el, dataIndex, elOption, animatableModel, data) {
  61725. var newChildren = elOption.children;
  61726. var newLen = newChildren ? newChildren.length : 0;
  61727. var mergeChildren = elOption.$mergeChildren;
  61728. // `diffChildrenByName` has been deprecated.
  61729. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  61730. var notMerge = mergeChildren === false;
  61731. // For better performance on roam update, only enter if necessary.
  61732. if (!newLen && !byName && !notMerge) {
  61733. return;
  61734. }
  61735. if (byName) {
  61736. diffGroupChildren({
  61737. oldChildren: el.children() || [],
  61738. newChildren: newChildren || [],
  61739. dataIndex: dataIndex,
  61740. animatableModel: animatableModel,
  61741. group: el,
  61742. data: data
  61743. });
  61744. return;
  61745. }
  61746. notMerge && el.removeAll();
  61747. // Mapping children of a group simply by index, which
  61748. // might be better performance.
  61749. var index = 0;
  61750. for (; index < newLen; index++) {
  61751. newChildren[index] && doCreateOrUpdate(
  61752. el.childAt(index),
  61753. dataIndex,
  61754. newChildren[index],
  61755. animatableModel,
  61756. el,
  61757. data
  61758. );
  61759. }
  61760. if (__DEV__) {
  61761. assert$1(
  61762. !notMerge || el.childCount() === index,
  61763. 'MUST NOT contain empty item in children array when `group.$mergeChildren` is `false`.'
  61764. );
  61765. }
  61766. }
  61767. function diffGroupChildren(context) {
  61768. (new DataDiffer(
  61769. context.oldChildren,
  61770. context.newChildren,
  61771. getKey,
  61772. getKey,
  61773. context
  61774. ))
  61775. .add(processAddUpdate)
  61776. .update(processAddUpdate)
  61777. .remove(processRemove)
  61778. .execute();
  61779. }
  61780. function getKey(item, idx) {
  61781. var name = item && item.name;
  61782. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  61783. }
  61784. function processAddUpdate(newIndex, oldIndex) {
  61785. var context = this.context;
  61786. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  61787. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  61788. doCreateOrUpdate(
  61789. child,
  61790. context.dataIndex,
  61791. childOption,
  61792. context.animatableModel,
  61793. context.group,
  61794. context.data
  61795. );
  61796. }
  61797. function processRemove(oldIndex) {
  61798. var context = this.context;
  61799. var child = context.oldChildren[oldIndex];
  61800. child && context.group.remove(child);
  61801. }
  61802. function getPathData(shape) {
  61803. // "d" follows the SVG convention.
  61804. return shape && (shape.pathData || shape.d);
  61805. }
  61806. function hasOwnPathData(shape) {
  61807. return shape && (shape.hasOwnProperty('pathData') || shape.hasOwnProperty('d'));
  61808. }
  61809. function hasOwn(host, prop) {
  61810. return host && host.hasOwnProperty(prop);
  61811. }
  61812. /*
  61813. * Licensed to the Apache Software Foundation (ASF) under one
  61814. * or more contributor license agreements. See the NOTICE file
  61815. * distributed with this work for additional information
  61816. * regarding copyright ownership. The ASF licenses this file
  61817. * to you under the Apache License, Version 2.0 (the
  61818. * "License"); you may not use this file except in compliance
  61819. * with the License. You may obtain a copy of the License at
  61820. *
  61821. * http://www.apache.org/licenses/LICENSE-2.0
  61822. *
  61823. * Unless required by applicable law or agreed to in writing,
  61824. * software distributed under the License is distributed on an
  61825. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61826. * KIND, either express or implied. See the License for the
  61827. * specific language governing permissions and limitations
  61828. * under the License.
  61829. */
  61830. // -------------
  61831. // Preprocessor
  61832. // -------------
  61833. registerPreprocessor(function (option) {
  61834. var graphicOption = option.graphic;
  61835. // Convert
  61836. // {graphic: [{left: 10, type: 'circle'}, ...]}
  61837. // or
  61838. // {graphic: {left: 10, type: 'circle'}}
  61839. // to
  61840. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  61841. if (isArray(graphicOption)) {
  61842. if (!graphicOption[0] || !graphicOption[0].elements) {
  61843. option.graphic = [{elements: graphicOption}];
  61844. }
  61845. else {
  61846. // Only one graphic instance can be instantiated. (We dont
  61847. // want that too many views are created in echarts._viewMap)
  61848. option.graphic = [option.graphic[0]];
  61849. }
  61850. }
  61851. else if (graphicOption && !graphicOption.elements) {
  61852. option.graphic = [{elements: [graphicOption]}];
  61853. }
  61854. });
  61855. // ------
  61856. // Model
  61857. // ------
  61858. var GraphicModel = extendComponentModel({
  61859. type: 'graphic',
  61860. defaultOption: {
  61861. // Extra properties for each elements:
  61862. //
  61863. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  61864. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  61865. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  61866. // This mechanism is useful when you want to position a group/element
  61867. // against the right side or the center of this container.
  61868. //
  61869. // width/height: (can only be pixel value, default 0)
  61870. // Only be used to specify contianer(group) size, if needed. And
  61871. // can not be percentage value (like '33%'). See the reason in the
  61872. // layout algorithm below.
  61873. //
  61874. // bounding: (enum: 'all' (default) | 'raw')
  61875. // Specify how to calculate boundingRect when locating.
  61876. // 'all': Get uioned and transformed boundingRect
  61877. // from both itself and its descendants.
  61878. // This mode simplies confining a group of elements in the bounding
  61879. // of their ancester container (e.g., using 'right: 0').
  61880. // 'raw': Only use the boundingRect of itself and before transformed.
  61881. // This mode is similar to css behavior, which is useful when you
  61882. // want an element to be able to overflow its container. (Consider
  61883. // a rotated circle needs to be located in a corner.)
  61884. // info: custom info. enables user to mount some info on elements and use them
  61885. // in event handlers. Update them only when user specified, otherwise, remain.
  61886. // Note: elements is always behind its ancestors in this elements array.
  61887. elements: [],
  61888. parentId: null
  61889. },
  61890. /**
  61891. * Save el options for the sake of the performance (only update modified graphics).
  61892. * The order is the same as those in option. (ancesters -> descendants)
  61893. *
  61894. * @private
  61895. * @type {Array.<Object>}
  61896. */
  61897. _elOptionsToUpdate: null,
  61898. /**
  61899. * @override
  61900. */
  61901. mergeOption: function (option) {
  61902. // Prevent default merge to elements
  61903. var elements = this.option.elements;
  61904. this.option.elements = null;
  61905. GraphicModel.superApply(this, 'mergeOption', arguments);
  61906. this.option.elements = elements;
  61907. },
  61908. /**
  61909. * @override
  61910. */
  61911. optionUpdated: function (newOption, isInit) {
  61912. var thisOption = this.option;
  61913. var newList = (isInit ? thisOption : newOption).elements;
  61914. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  61915. var flattenedList = [];
  61916. this._flatten(newList, flattenedList);
  61917. var mappingResult = mappingToExists(existList, flattenedList);
  61918. makeIdAndName(mappingResult);
  61919. // Clear elOptionsToUpdate
  61920. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  61921. each$1(mappingResult, function (resultItem, index) {
  61922. var newElOption = resultItem.option;
  61923. if (__DEV__) {
  61924. assert$1(
  61925. isObject$1(newElOption) || resultItem.exist,
  61926. 'Empty graphic option definition'
  61927. );
  61928. }
  61929. if (!newElOption) {
  61930. return;
  61931. }
  61932. elOptionsToUpdate.push(newElOption);
  61933. setKeyInfoToNewElOption(resultItem, newElOption);
  61934. mergeNewElOptionToExist(existList, index, newElOption);
  61935. setLayoutInfoToExist(existList[index], newElOption);
  61936. }, this);
  61937. // Clean
  61938. for (var i = existList.length - 1; i >= 0; i--) {
  61939. if (existList[i] == null) {
  61940. existList.splice(i, 1);
  61941. }
  61942. else {
  61943. // $action should be volatile, otherwise option gotten from
  61944. // `getOption` will contain unexpected $action.
  61945. delete existList[i].$action;
  61946. }
  61947. }
  61948. },
  61949. /**
  61950. * Convert
  61951. * [{
  61952. * type: 'group',
  61953. * id: 'xx',
  61954. * children: [{type: 'circle'}, {type: 'polygon'}]
  61955. * }]
  61956. * to
  61957. * [
  61958. * {type: 'group', id: 'xx'},
  61959. * {type: 'circle', parentId: 'xx'},
  61960. * {type: 'polygon', parentId: 'xx'}
  61961. * ]
  61962. *
  61963. * @private
  61964. * @param {Array.<Object>} optionList option list
  61965. * @param {Array.<Object>} result result of flatten
  61966. * @param {Object} parentOption parent option
  61967. */
  61968. _flatten: function (optionList, result, parentOption) {
  61969. each$1(optionList, function (option) {
  61970. if (!option) {
  61971. return;
  61972. }
  61973. if (parentOption) {
  61974. option.parentOption = parentOption;
  61975. }
  61976. result.push(option);
  61977. var children = option.children;
  61978. if (option.type === 'group' && children) {
  61979. this._flatten(children, result, option);
  61980. }
  61981. // Deleting for JSON output, and for not affecting group creation.
  61982. delete option.children;
  61983. }, this);
  61984. },
  61985. // FIXME
  61986. // Pass to view using payload? setOption has a payload?
  61987. useElOptionsToUpdate: function () {
  61988. var els = this._elOptionsToUpdate;
  61989. // Clear to avoid render duplicately when zooming.
  61990. this._elOptionsToUpdate = null;
  61991. return els;
  61992. }
  61993. });
  61994. // -----
  61995. // View
  61996. // -----
  61997. extendComponentView({
  61998. type: 'graphic',
  61999. /**
  62000. * @override
  62001. */
  62002. init: function (ecModel, api) {
  62003. /**
  62004. * @private
  62005. * @type {module:zrender/core/util.HashMap}
  62006. */
  62007. this._elMap = createHashMap();
  62008. /**
  62009. * @private
  62010. * @type {module:echarts/graphic/GraphicModel}
  62011. */
  62012. this._lastGraphicModel;
  62013. },
  62014. /**
  62015. * @override
  62016. */
  62017. render: function (graphicModel, ecModel, api) {
  62018. // Having leveraged between use cases and algorithm complexity, a very
  62019. // simple layout mechanism is used:
  62020. // The size(width/height) can be determined by itself or its parent (not
  62021. // implemented yet), but can not by its children. (Top-down travel)
  62022. // The location(x/y) can be determined by the bounding rect of itself
  62023. // (can including its descendants or not) and the size of its parent.
  62024. // (Bottom-up travel)
  62025. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  62026. // view will be reused.
  62027. if (graphicModel !== this._lastGraphicModel) {
  62028. this._clear();
  62029. }
  62030. this._lastGraphicModel = graphicModel;
  62031. this._updateElements(graphicModel);
  62032. this._relocate(graphicModel, api);
  62033. },
  62034. /**
  62035. * Update graphic elements.
  62036. *
  62037. * @private
  62038. * @param {Object} graphicModel graphic model
  62039. */
  62040. _updateElements: function (graphicModel) {
  62041. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  62042. if (!elOptionsToUpdate) {
  62043. return;
  62044. }
  62045. var elMap = this._elMap;
  62046. var rootGroup = this.group;
  62047. // Top-down tranverse to assign graphic settings to each elements.
  62048. each$1(elOptionsToUpdate, function (elOption) {
  62049. var $action = elOption.$action;
  62050. var id = elOption.id;
  62051. var existEl = elMap.get(id);
  62052. var parentId = elOption.parentId;
  62053. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  62054. var elOptionStyle = elOption.style;
  62055. if (elOption.type === 'text' && elOptionStyle) {
  62056. // In top/bottom mode, textVerticalAlign should not be used, which cause
  62057. // inaccurately locating.
  62058. if (elOption.hv && elOption.hv[1]) {
  62059. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  62060. }
  62061. // Compatible with previous setting: both support fill and textFill,
  62062. // stroke and textStroke.
  62063. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  62064. elOptionStyle.textFill = elOptionStyle.fill
  62065. );
  62066. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  62067. elOptionStyle.textStroke = elOptionStyle.stroke
  62068. );
  62069. }
  62070. // Remove unnecessary props to avoid potential problems.
  62071. var elOptionCleaned = getCleanedElOption(elOption);
  62072. // For simple, do not support parent change, otherwise reorder is needed.
  62073. if (__DEV__) {
  62074. existEl && assert$1(
  62075. targetElParent === existEl.parent,
  62076. 'Changing parent is not supported.'
  62077. );
  62078. }
  62079. if (!$action || $action === 'merge') {
  62080. existEl
  62081. ? existEl.attr(elOptionCleaned)
  62082. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  62083. }
  62084. else if ($action === 'replace') {
  62085. removeEl(existEl, elMap);
  62086. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  62087. }
  62088. else if ($action === 'remove') {
  62089. removeEl(existEl, elMap);
  62090. }
  62091. var el = elMap.get(id);
  62092. if (el) {
  62093. el.__ecGraphicWidth = elOption.width;
  62094. el.__ecGraphicHeight = elOption.height;
  62095. setEventData(el, graphicModel, elOption);
  62096. }
  62097. });
  62098. },
  62099. /**
  62100. * Locate graphic elements.
  62101. *
  62102. * @private
  62103. * @param {Object} graphicModel graphic model
  62104. * @param {module:echarts/ExtensionAPI} api extension API
  62105. */
  62106. _relocate: function (graphicModel, api) {
  62107. var elOptions = graphicModel.option.elements;
  62108. var rootGroup = this.group;
  62109. var elMap = this._elMap;
  62110. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  62111. for (var i = elOptions.length - 1; i >= 0; i--) {
  62112. var elOption = elOptions[i];
  62113. var el = elMap.get(elOption.id);
  62114. if (!el) {
  62115. continue;
  62116. }
  62117. var parentEl = el.parent;
  62118. var containerInfo = parentEl === rootGroup
  62119. ? {
  62120. width: api.getWidth(),
  62121. height: api.getHeight()
  62122. }
  62123. : { // Like 'position:absolut' in css, default 0.
  62124. width: parentEl.__ecGraphicWidth || 0,
  62125. height: parentEl.__ecGraphicHeight || 0
  62126. };
  62127. positionElement(
  62128. el, elOption, containerInfo, null,
  62129. {hv: elOption.hv, boundingMode: elOption.bounding}
  62130. );
  62131. }
  62132. },
  62133. /**
  62134. * Clear all elements.
  62135. *
  62136. * @private
  62137. */
  62138. _clear: function () {
  62139. var elMap = this._elMap;
  62140. elMap.each(function (el) {
  62141. removeEl(el, elMap);
  62142. });
  62143. this._elMap = createHashMap();
  62144. },
  62145. /**
  62146. * @override
  62147. */
  62148. dispose: function () {
  62149. this._clear();
  62150. }
  62151. });
  62152. function createEl$1(id, targetElParent, elOption, elMap) {
  62153. var graphicType = elOption.type;
  62154. if (__DEV__) {
  62155. assert$1(graphicType, 'graphic type MUST be set');
  62156. }
  62157. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  62158. if (__DEV__) {
  62159. assert$1(Clz, 'graphic type can not be found');
  62160. }
  62161. var el = new Clz(elOption);
  62162. targetElParent.add(el);
  62163. elMap.set(id, el);
  62164. el.__ecGraphicId = id;
  62165. }
  62166. function removeEl(existEl, elMap) {
  62167. var existElParent = existEl && existEl.parent;
  62168. if (existElParent) {
  62169. existEl.type === 'group' && existEl.traverse(function (el) {
  62170. removeEl(el, elMap);
  62171. });
  62172. elMap.removeKey(existEl.__ecGraphicId);
  62173. existElParent.remove(existEl);
  62174. }
  62175. }
  62176. // Remove unnecessary props to avoid potential problems.
  62177. function getCleanedElOption(elOption) {
  62178. elOption = extend({}, elOption);
  62179. each$1(
  62180. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  62181. function (name) {
  62182. delete elOption[name];
  62183. }
  62184. );
  62185. return elOption;
  62186. }
  62187. function isSetLoc(obj, props) {
  62188. var isSet;
  62189. each$1(props, function (prop) {
  62190. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  62191. });
  62192. return isSet;
  62193. }
  62194. function setKeyInfoToNewElOption(resultItem, newElOption) {
  62195. var existElOption = resultItem.exist;
  62196. // Set id and type after id assigned.
  62197. newElOption.id = resultItem.keyInfo.id;
  62198. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  62199. // Set parent id if not specified
  62200. if (newElOption.parentId == null) {
  62201. var newElParentOption = newElOption.parentOption;
  62202. if (newElParentOption) {
  62203. newElOption.parentId = newElParentOption.id;
  62204. }
  62205. else if (existElOption) {
  62206. newElOption.parentId = existElOption.parentId;
  62207. }
  62208. }
  62209. // Clear
  62210. newElOption.parentOption = null;
  62211. }
  62212. function mergeNewElOptionToExist(existList, index, newElOption) {
  62213. // Update existing options, for `getOption` feature.
  62214. var newElOptCopy = extend({}, newElOption);
  62215. var existElOption = existList[index];
  62216. var $action = newElOption.$action || 'merge';
  62217. if ($action === 'merge') {
  62218. if (existElOption) {
  62219. if (__DEV__) {
  62220. var newType = newElOption.type;
  62221. assert$1(
  62222. !newType || existElOption.type === newType,
  62223. 'Please set $action: "replace" to change `type`'
  62224. );
  62225. }
  62226. // We can ensure that newElOptCopy and existElOption are not
  62227. // the same object, so `merge` will not change newElOptCopy.
  62228. merge(existElOption, newElOptCopy, true);
  62229. // Rigid body, use ignoreSize.
  62230. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  62231. // Will be used in render.
  62232. copyLayoutParams(newElOption, existElOption);
  62233. }
  62234. else {
  62235. existList[index] = newElOptCopy;
  62236. }
  62237. }
  62238. else if ($action === 'replace') {
  62239. existList[index] = newElOptCopy;
  62240. }
  62241. else if ($action === 'remove') {
  62242. // null will be cleaned later.
  62243. existElOption && (existList[index] = null);
  62244. }
  62245. }
  62246. function setLayoutInfoToExist(existItem, newElOption) {
  62247. if (!existItem) {
  62248. return;
  62249. }
  62250. existItem.hv = newElOption.hv = [
  62251. // Rigid body, dont care `width`.
  62252. isSetLoc(newElOption, ['left', 'right']),
  62253. // Rigid body, dont care `height`.
  62254. isSetLoc(newElOption, ['top', 'bottom'])
  62255. ];
  62256. // Give default group size. Otherwise layout error may occur.
  62257. if (existItem.type === 'group') {
  62258. existItem.width == null && (existItem.width = newElOption.width = 0);
  62259. existItem.height == null && (existItem.height = newElOption.height = 0);
  62260. }
  62261. }
  62262. function setEventData(el, graphicModel, elOption) {
  62263. var eventData = el.eventData;
  62264. // Simple optimize for large amount of elements that no need event.
  62265. if (!el.silent && !el.ignore && !eventData) {
  62266. eventData = el.eventData = {
  62267. componentType: 'graphic',
  62268. componentIndex: graphicModel.componentIndex,
  62269. name: el.name
  62270. };
  62271. }
  62272. // `elOption.info` enables user to mount some info on
  62273. // elements and use them in event handlers.
  62274. if (eventData) {
  62275. eventData.info = el.info;
  62276. }
  62277. }
  62278. /*
  62279. * Licensed to the Apache Software Foundation (ASF) under one
  62280. * or more contributor license agreements. See the NOTICE file
  62281. * distributed with this work for additional information
  62282. * regarding copyright ownership. The ASF licenses this file
  62283. * to you under the Apache License, Version 2.0 (the
  62284. * "License"); you may not use this file except in compliance
  62285. * with the License. You may obtain a copy of the License at
  62286. *
  62287. * http://www.apache.org/licenses/LICENSE-2.0
  62288. *
  62289. * Unless required by applicable law or agreed to in writing,
  62290. * software distributed under the License is distributed on an
  62291. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62292. * KIND, either express or implied. See the License for the
  62293. * specific language governing permissions and limitations
  62294. * under the License.
  62295. */
  62296. /*
  62297. * Licensed to the Apache Software Foundation (ASF) under one
  62298. * or more contributor license agreements. See the NOTICE file
  62299. * distributed with this work for additional information
  62300. * regarding copyright ownership. The ASF licenses this file
  62301. * to you under the Apache License, Version 2.0 (the
  62302. * "License"); you may not use this file except in compliance
  62303. * with the License. You may obtain a copy of the License at
  62304. *
  62305. * http://www.apache.org/licenses/LICENSE-2.0
  62306. *
  62307. * Unless required by applicable law or agreed to in writing,
  62308. * software distributed under the License is distributed on an
  62309. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62310. * KIND, either express or implied. See the License for the
  62311. * specific language governing permissions and limitations
  62312. * under the License.
  62313. */
  62314. var LegendModel = extendComponentModel({
  62315. type: 'legend.plain',
  62316. dependencies: ['series'],
  62317. layoutMode: {
  62318. type: 'box',
  62319. // legend.width/height are maxWidth/maxHeight actually,
  62320. // whereas realy width/height is calculated by its content.
  62321. // (Setting {left: 10, right: 10} does not make sense).
  62322. // So consider the case:
  62323. // `setOption({legend: {left: 10});`
  62324. // then `setOption({legend: {right: 10});`
  62325. // The previous `left` should be cleared by setting `ignoreSize`.
  62326. ignoreSize: true
  62327. },
  62328. init: function (option, parentModel, ecModel) {
  62329. this.mergeDefaultAndTheme(option, ecModel);
  62330. option.selected = option.selected || {};
  62331. },
  62332. mergeOption: function (option) {
  62333. LegendModel.superCall(this, 'mergeOption', option);
  62334. },
  62335. optionUpdated: function () {
  62336. this._updateData(this.ecModel);
  62337. var legendData = this._data;
  62338. // If selectedMode is single, try to select one
  62339. if (legendData[0] && this.get('selectedMode') === 'single') {
  62340. var hasSelected = false;
  62341. // If has any selected in option.selected
  62342. for (var i = 0; i < legendData.length; i++) {
  62343. var name = legendData[i].get('name');
  62344. if (this.isSelected(name)) {
  62345. // Force to unselect others
  62346. this.select(name);
  62347. hasSelected = true;
  62348. break;
  62349. }
  62350. }
  62351. // Try select the first if selectedMode is single
  62352. !hasSelected && this.select(legendData[0].get('name'));
  62353. }
  62354. },
  62355. _updateData: function (ecModel) {
  62356. var potentialData = [];
  62357. var availableNames = [];
  62358. ecModel.eachRawSeries(function (seriesModel) {
  62359. var seriesName = seriesModel.name;
  62360. availableNames.push(seriesName);
  62361. var isPotential;
  62362. if (seriesModel.legendDataProvider) {
  62363. var data = seriesModel.legendDataProvider();
  62364. var names = data.mapArray(data.getName);
  62365. if (!ecModel.isSeriesFiltered(seriesModel)) {
  62366. availableNames = availableNames.concat(names);
  62367. }
  62368. if (names.length) {
  62369. potentialData = potentialData.concat(names);
  62370. }
  62371. else {
  62372. isPotential = true;
  62373. }
  62374. }
  62375. else {
  62376. isPotential = true;
  62377. }
  62378. if (isPotential && isNameSpecified(seriesModel)) {
  62379. potentialData.push(seriesModel.name);
  62380. }
  62381. });
  62382. /**
  62383. * @type {Array.<string>}
  62384. * @private
  62385. */
  62386. this._availableNames = availableNames;
  62387. // If legend.data not specified in option, use availableNames as data,
  62388. // which is convinient for user preparing option.
  62389. var rawData = this.get('data') || potentialData;
  62390. var legendData = map(rawData, function (dataItem) {
  62391. // Can be string or number
  62392. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  62393. dataItem = {
  62394. name: dataItem
  62395. };
  62396. }
  62397. return new Model(dataItem, this, this.ecModel);
  62398. }, this);
  62399. /**
  62400. * @type {Array.<module:echarts/model/Model>}
  62401. * @private
  62402. */
  62403. this._data = legendData;
  62404. },
  62405. /**
  62406. * @return {Array.<module:echarts/model/Model>}
  62407. */
  62408. getData: function () {
  62409. return this._data;
  62410. },
  62411. /**
  62412. * @param {string} name
  62413. */
  62414. select: function (name) {
  62415. var selected = this.option.selected;
  62416. var selectedMode = this.get('selectedMode');
  62417. if (selectedMode === 'single') {
  62418. var data = this._data;
  62419. each$1(data, function (dataItem) {
  62420. selected[dataItem.get('name')] = false;
  62421. });
  62422. }
  62423. selected[name] = true;
  62424. },
  62425. /**
  62426. * @param {string} name
  62427. */
  62428. unSelect: function (name) {
  62429. if (this.get('selectedMode') !== 'single') {
  62430. this.option.selected[name] = false;
  62431. }
  62432. },
  62433. /**
  62434. * @param {string} name
  62435. */
  62436. toggleSelected: function (name) {
  62437. var selected = this.option.selected;
  62438. // Default is true
  62439. if (!selected.hasOwnProperty(name)) {
  62440. selected[name] = true;
  62441. }
  62442. this[selected[name] ? 'unSelect' : 'select'](name);
  62443. },
  62444. /**
  62445. * @param {string} name
  62446. */
  62447. isSelected: function (name) {
  62448. var selected = this.option.selected;
  62449. return !(selected.hasOwnProperty(name) && !selected[name])
  62450. && indexOf(this._availableNames, name) >= 0;
  62451. },
  62452. defaultOption: {
  62453. // 一级层叠
  62454. zlevel: 0,
  62455. // 二级层叠
  62456. z: 4,
  62457. show: true,
  62458. // 布局方式,默认为水平布局,可选为:
  62459. // 'horizontal' | 'vertical'
  62460. orient: 'horizontal',
  62461. left: 'center',
  62462. // right: 'center',
  62463. top: 0,
  62464. // bottom: null,
  62465. // 水平对齐
  62466. // 'auto' | 'left' | 'right'
  62467. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  62468. align: 'auto',
  62469. backgroundColor: 'rgba(0,0,0,0)',
  62470. // 图例边框颜色
  62471. borderColor: '#ccc',
  62472. borderRadius: 0,
  62473. // 图例边框线宽,单位px,默认为0(无边框)
  62474. borderWidth: 0,
  62475. // 图例内边距,单位px,默认各方向内边距为5,
  62476. // 接受数组分别设定上右下左边距,同css
  62477. padding: 5,
  62478. // 各个item之间的间隔,单位px,默认为10,
  62479. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  62480. itemGap: 10,
  62481. // 图例图形宽度
  62482. itemWidth: 25,
  62483. // 图例图形高度
  62484. itemHeight: 14,
  62485. // 图例关闭时候的颜色
  62486. inactiveColor: '#ccc',
  62487. textStyle: {
  62488. // 图例文字颜色
  62489. color: '#333'
  62490. },
  62491. // formatter: '',
  62492. // 选择模式,默认开启图例开关
  62493. selectedMode: true,
  62494. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  62495. // selected: null,
  62496. // 图例内容(详见legend.data,数组中每一项代表一个item
  62497. // data: [],
  62498. // Tooltip 相关配置
  62499. tooltip: {
  62500. show: false
  62501. }
  62502. }
  62503. });
  62504. /*
  62505. * Licensed to the Apache Software Foundation (ASF) under one
  62506. * or more contributor license agreements. See the NOTICE file
  62507. * distributed with this work for additional information
  62508. * regarding copyright ownership. The ASF licenses this file
  62509. * to you under the Apache License, Version 2.0 (the
  62510. * "License"); you may not use this file except in compliance
  62511. * with the License. You may obtain a copy of the License at
  62512. *
  62513. * http://www.apache.org/licenses/LICENSE-2.0
  62514. *
  62515. * Unless required by applicable law or agreed to in writing,
  62516. * software distributed under the License is distributed on an
  62517. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62518. * KIND, either express or implied. See the License for the
  62519. * specific language governing permissions and limitations
  62520. * under the License.
  62521. */
  62522. function legendSelectActionHandler(methodName, payload, ecModel) {
  62523. var selectedMap = {};
  62524. var isToggleSelect = methodName === 'toggleSelected';
  62525. var isSelected;
  62526. // Update all legend components
  62527. ecModel.eachComponent('legend', function (legendModel) {
  62528. if (isToggleSelect && isSelected != null) {
  62529. // Force other legend has same selected status
  62530. // Or the first is toggled to true and other are toggled to false
  62531. // In the case one legend has some item unSelected in option. And if other legend
  62532. // doesn't has the item, they will assume it is selected.
  62533. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  62534. }
  62535. else {
  62536. legendModel[methodName](payload.name);
  62537. isSelected = legendModel.isSelected(payload.name);
  62538. }
  62539. var legendData = legendModel.getData();
  62540. each$1(legendData, function (model) {
  62541. var name = model.get('name');
  62542. // Wrap element
  62543. if (name === '\n' || name === '') {
  62544. return;
  62545. }
  62546. var isItemSelected = legendModel.isSelected(name);
  62547. if (selectedMap.hasOwnProperty(name)) {
  62548. // Unselected if any legend is unselected
  62549. selectedMap[name] = selectedMap[name] && isItemSelected;
  62550. }
  62551. else {
  62552. selectedMap[name] = isItemSelected;
  62553. }
  62554. });
  62555. });
  62556. // Return the event explicitly
  62557. return {
  62558. name: payload.name,
  62559. selected: selectedMap
  62560. };
  62561. }
  62562. /**
  62563. * @event legendToggleSelect
  62564. * @type {Object}
  62565. * @property {string} type 'legendToggleSelect'
  62566. * @property {string} [from]
  62567. * @property {string} name Series name or data item name
  62568. */
  62569. registerAction(
  62570. 'legendToggleSelect', 'legendselectchanged',
  62571. curry(legendSelectActionHandler, 'toggleSelected')
  62572. );
  62573. /**
  62574. * @event legendSelect
  62575. * @type {Object}
  62576. * @property {string} type 'legendSelect'
  62577. * @property {string} name Series name or data item name
  62578. */
  62579. registerAction(
  62580. 'legendSelect', 'legendselected',
  62581. curry(legendSelectActionHandler, 'select')
  62582. );
  62583. /**
  62584. * @event legendUnSelect
  62585. * @type {Object}
  62586. * @property {string} type 'legendUnSelect'
  62587. * @property {string} name Series name or data item name
  62588. */
  62589. registerAction(
  62590. 'legendUnSelect', 'legendunselected',
  62591. curry(legendSelectActionHandler, 'unSelect')
  62592. );
  62593. /*
  62594. * Licensed to the Apache Software Foundation (ASF) under one
  62595. * or more contributor license agreements. See the NOTICE file
  62596. * distributed with this work for additional information
  62597. * regarding copyright ownership. The ASF licenses this file
  62598. * to you under the Apache License, Version 2.0 (the
  62599. * "License"); you may not use this file except in compliance
  62600. * with the License. You may obtain a copy of the License at
  62601. *
  62602. * http://www.apache.org/licenses/LICENSE-2.0
  62603. *
  62604. * Unless required by applicable law or agreed to in writing,
  62605. * software distributed under the License is distributed on an
  62606. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62607. * KIND, either express or implied. See the License for the
  62608. * specific language governing permissions and limitations
  62609. * under the License.
  62610. */
  62611. /**
  62612. * Layout list like component.
  62613. * It will box layout each items in group of component and then position the whole group in the viewport
  62614. * @param {module:zrender/group/Group} group
  62615. * @param {module:echarts/model/Component} componentModel
  62616. * @param {module:echarts/ExtensionAPI}
  62617. */
  62618. function layout$3(group, componentModel, api) {
  62619. var boxLayoutParams = componentModel.getBoxLayoutParams();
  62620. var padding = componentModel.get('padding');
  62621. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  62622. var rect = getLayoutRect(
  62623. boxLayoutParams,
  62624. viewportSize,
  62625. padding
  62626. );
  62627. box(
  62628. componentModel.get('orient'),
  62629. group,
  62630. componentModel.get('itemGap'),
  62631. rect.width,
  62632. rect.height
  62633. );
  62634. positionElement(
  62635. group,
  62636. boxLayoutParams,
  62637. viewportSize,
  62638. padding
  62639. );
  62640. }
  62641. function makeBackground(rect, componentModel) {
  62642. var padding = normalizeCssArray$1(
  62643. componentModel.get('padding')
  62644. );
  62645. var style = componentModel.getItemStyle(['color', 'opacity']);
  62646. style.fill = componentModel.get('backgroundColor');
  62647. var rect = new Rect({
  62648. shape: {
  62649. x: rect.x - padding[3],
  62650. y: rect.y - padding[0],
  62651. width: rect.width + padding[1] + padding[3],
  62652. height: rect.height + padding[0] + padding[2],
  62653. r: componentModel.get('borderRadius')
  62654. },
  62655. style: style,
  62656. silent: true,
  62657. z2: -1
  62658. });
  62659. // FIXME
  62660. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  62661. // and background rect when setting like `left: 0`, `top: 0`.
  62662. // graphic.subPixelOptimizeRect(rect);
  62663. return rect;
  62664. }
  62665. /*
  62666. * Licensed to the Apache Software Foundation (ASF) under one
  62667. * or more contributor license agreements. See the NOTICE file
  62668. * distributed with this work for additional information
  62669. * regarding copyright ownership. The ASF licenses this file
  62670. * to you under the Apache License, Version 2.0 (the
  62671. * "License"); you may not use this file except in compliance
  62672. * with the License. You may obtain a copy of the License at
  62673. *
  62674. * http://www.apache.org/licenses/LICENSE-2.0
  62675. *
  62676. * Unless required by applicable law or agreed to in writing,
  62677. * software distributed under the License is distributed on an
  62678. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62679. * KIND, either express or implied. See the License for the
  62680. * specific language governing permissions and limitations
  62681. * under the License.
  62682. */
  62683. var curry$4 = curry;
  62684. var each$16 = each$1;
  62685. var Group$3 = Group;
  62686. var LegendView = extendComponentView({
  62687. type: 'legend.plain',
  62688. newlineDisabled: false,
  62689. /**
  62690. * @override
  62691. */
  62692. init: function () {
  62693. /**
  62694. * @private
  62695. * @type {module:zrender/container/Group}
  62696. */
  62697. this.group.add(this._contentGroup = new Group$3());
  62698. /**
  62699. * @private
  62700. * @type {module:zrender/Element}
  62701. */
  62702. this._backgroundEl;
  62703. /**
  62704. * If first rendering, `contentGroup.position` is [0, 0], which
  62705. * does not make sense and may cause unexepcted animation if adopted.
  62706. * @private
  62707. * @type {boolean}
  62708. */
  62709. this._isFirstRender = true;
  62710. },
  62711. /**
  62712. * @protected
  62713. */
  62714. getContentGroup: function () {
  62715. return this._contentGroup;
  62716. },
  62717. /**
  62718. * @override
  62719. */
  62720. render: function (legendModel, ecModel, api) {
  62721. var isFirstRender = this._isFirstRender;
  62722. this._isFirstRender = false;
  62723. this.resetInner();
  62724. if (!legendModel.get('show', true)) {
  62725. return;
  62726. }
  62727. var itemAlign = legendModel.get('align');
  62728. if (!itemAlign || itemAlign === 'auto') {
  62729. itemAlign = (
  62730. legendModel.get('left') === 'right'
  62731. && legendModel.get('orient') === 'vertical'
  62732. ) ? 'right' : 'left';
  62733. }
  62734. this.renderInner(itemAlign, legendModel, ecModel, api);
  62735. // Perform layout.
  62736. var positionInfo = legendModel.getBoxLayoutParams();
  62737. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  62738. var padding = legendModel.get('padding');
  62739. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  62740. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender);
  62741. // Place mainGroup, based on the calculated `mainRect`.
  62742. var layoutRect = getLayoutRect(
  62743. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  62744. viewportSize,
  62745. padding
  62746. );
  62747. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  62748. // Render background after group is layout.
  62749. this.group.add(
  62750. this._backgroundEl = makeBackground(mainRect, legendModel)
  62751. );
  62752. },
  62753. /**
  62754. * @protected
  62755. */
  62756. resetInner: function () {
  62757. this.getContentGroup().removeAll();
  62758. this._backgroundEl && this.group.remove(this._backgroundEl);
  62759. },
  62760. /**
  62761. * @protected
  62762. */
  62763. renderInner: function (itemAlign, legendModel, ecModel, api) {
  62764. var contentGroup = this.getContentGroup();
  62765. var legendDrawnMap = createHashMap();
  62766. var selectMode = legendModel.get('selectedMode');
  62767. var excludeSeriesId = [];
  62768. ecModel.eachRawSeries(function (seriesModel) {
  62769. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  62770. });
  62771. each$16(legendModel.getData(), function (itemModel, dataIndex) {
  62772. var name = itemModel.get('name');
  62773. // Use empty string or \n as a newline string
  62774. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  62775. contentGroup.add(new Group$3({
  62776. newline: true
  62777. }));
  62778. return;
  62779. }
  62780. // Representitive series.
  62781. var seriesModel = ecModel.getSeriesByName(name)[0];
  62782. if (legendDrawnMap.get(name)) {
  62783. // Have been drawed
  62784. return;
  62785. }
  62786. // Series legend
  62787. if (seriesModel) {
  62788. var data = seriesModel.getData();
  62789. var color = data.getVisual('color');
  62790. // If color is a callback function
  62791. if (typeof color === 'function') {
  62792. // Use the first data
  62793. color = color(seriesModel.getDataParams(0));
  62794. }
  62795. // Using rect symbol defaultly
  62796. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  62797. var symbolType = data.getVisual('symbol');
  62798. var itemGroup = this._createItem(
  62799. name, dataIndex, itemModel, legendModel,
  62800. legendSymbolType, symbolType,
  62801. itemAlign, color,
  62802. selectMode
  62803. );
  62804. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  62805. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId))
  62806. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  62807. legendDrawnMap.set(name, true);
  62808. }
  62809. else {
  62810. // Data legend of pie, funnel
  62811. ecModel.eachRawSeries(function (seriesModel) {
  62812. // In case multiple series has same data name
  62813. if (legendDrawnMap.get(name)) {
  62814. return;
  62815. }
  62816. if (seriesModel.legendDataProvider) {
  62817. var data = seriesModel.legendDataProvider();
  62818. var idx = data.indexOfName(name);
  62819. if (idx < 0) {
  62820. return;
  62821. }
  62822. var color = data.getItemVisual(idx, 'color');
  62823. var legendSymbolType = 'roundRect';
  62824. var itemGroup = this._createItem(
  62825. name, dataIndex, itemModel, legendModel,
  62826. legendSymbolType, null,
  62827. itemAlign, color,
  62828. selectMode
  62829. );
  62830. // FIXME: consider different series has items with the same name.
  62831. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  62832. // Should not specify the series name, consider legend controls
  62833. // more than one pie series.
  62834. .on('mouseover', curry$4(dispatchHighlightAction, null, name, api, excludeSeriesId))
  62835. .on('mouseout', curry$4(dispatchDownplayAction, null, name, api, excludeSeriesId));
  62836. legendDrawnMap.set(name, true);
  62837. }
  62838. }, this);
  62839. }
  62840. if (__DEV__) {
  62841. if (!legendDrawnMap.get(name)) {
  62842. console.warn(
  62843. name + ' series not exists. Legend data should be same with series name or data name.'
  62844. );
  62845. }
  62846. }
  62847. }, this);
  62848. },
  62849. _createItem: function (
  62850. name, dataIndex, itemModel, legendModel,
  62851. legendSymbolType, symbolType,
  62852. itemAlign, color, selectMode
  62853. ) {
  62854. var itemWidth = legendModel.get('itemWidth');
  62855. var itemHeight = legendModel.get('itemHeight');
  62856. var inactiveColor = legendModel.get('inactiveColor');
  62857. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  62858. var isSelected = legendModel.isSelected(name);
  62859. var itemGroup = new Group$3();
  62860. var textStyleModel = itemModel.getModel('textStyle');
  62861. var itemIcon = itemModel.get('icon');
  62862. var tooltipModel = itemModel.getModel('tooltip');
  62863. var legendGlobalTooltipModel = tooltipModel.parentModel;
  62864. // Use user given icon first
  62865. legendSymbolType = itemIcon || legendSymbolType;
  62866. itemGroup.add(createSymbol(
  62867. legendSymbolType,
  62868. 0,
  62869. 0,
  62870. itemWidth,
  62871. itemHeight,
  62872. isSelected ? color : inactiveColor,
  62873. // symbolKeepAspect default true for legend
  62874. symbolKeepAspect == null ? true : symbolKeepAspect
  62875. ));
  62876. // Compose symbols
  62877. // PENDING
  62878. if (!itemIcon && symbolType
  62879. // At least show one symbol, can't be all none
  62880. && ((symbolType !== legendSymbolType) || symbolType === 'none')
  62881. ) {
  62882. var size = itemHeight * 0.8;
  62883. if (symbolType === 'none') {
  62884. symbolType = 'circle';
  62885. }
  62886. // Put symbol in the center
  62887. itemGroup.add(createSymbol(
  62888. symbolType,
  62889. (itemWidth - size) / 2,
  62890. (itemHeight - size) / 2,
  62891. size,
  62892. size,
  62893. isSelected ? color : inactiveColor,
  62894. // symbolKeepAspect default true for legend
  62895. symbolKeepAspect == null ? true : symbolKeepAspect
  62896. ));
  62897. }
  62898. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  62899. var textAlign = itemAlign;
  62900. var formatter = legendModel.get('formatter');
  62901. var content = name;
  62902. if (typeof formatter === 'string' && formatter) {
  62903. content = formatter.replace('{name}', name != null ? name : '');
  62904. }
  62905. else if (typeof formatter === 'function') {
  62906. content = formatter(name);
  62907. }
  62908. itemGroup.add(new Text({
  62909. style: setTextStyle({}, textStyleModel, {
  62910. text: content,
  62911. x: textX,
  62912. y: itemHeight / 2,
  62913. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  62914. textAlign: textAlign,
  62915. textVerticalAlign: 'middle'
  62916. })
  62917. }));
  62918. // Add a invisible rect to increase the area of mouse hover
  62919. var hitRect = new Rect({
  62920. shape: itemGroup.getBoundingRect(),
  62921. invisible: true,
  62922. tooltip: tooltipModel.get('show') ? extend({
  62923. content: name,
  62924. // Defaul formatter
  62925. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  62926. return name;
  62927. },
  62928. formatterParams: {
  62929. componentType: 'legend',
  62930. legendIndex: legendModel.componentIndex,
  62931. name: name,
  62932. $vars: ['name']
  62933. }
  62934. }, tooltipModel.option) : null
  62935. });
  62936. itemGroup.add(hitRect);
  62937. itemGroup.eachChild(function (child) {
  62938. child.silent = true;
  62939. });
  62940. hitRect.silent = !selectMode;
  62941. this.getContentGroup().add(itemGroup);
  62942. setHoverStyle(itemGroup);
  62943. itemGroup.__legendDataIndex = dataIndex;
  62944. return itemGroup;
  62945. },
  62946. /**
  62947. * @protected
  62948. */
  62949. layoutInner: function (legendModel, itemAlign, maxSize) {
  62950. var contentGroup = this.getContentGroup();
  62951. // Place items in contentGroup.
  62952. box(
  62953. legendModel.get('orient'),
  62954. contentGroup,
  62955. legendModel.get('itemGap'),
  62956. maxSize.width,
  62957. maxSize.height
  62958. );
  62959. var contentRect = contentGroup.getBoundingRect();
  62960. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  62961. return this.group.getBoundingRect();
  62962. },
  62963. /**
  62964. * @protected
  62965. */
  62966. remove: function () {
  62967. this.getContentGroup().removeAll();
  62968. this._isFirstRender = true;
  62969. }
  62970. });
  62971. function dispatchSelectAction(name, api) {
  62972. api.dispatchAction({
  62973. type: 'legendToggleSelect',
  62974. name: name
  62975. });
  62976. }
  62977. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  62978. // If element hover will move to a hoverLayer.
  62979. var el = api.getZr().storage.getDisplayList()[0];
  62980. if (!(el && el.useHoverLayer)) {
  62981. api.dispatchAction({
  62982. type: 'highlight',
  62983. seriesName: seriesName,
  62984. name: dataName,
  62985. excludeSeriesId: excludeSeriesId
  62986. });
  62987. }
  62988. }
  62989. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  62990. // If element hover will move to a hoverLayer.
  62991. var el = api.getZr().storage.getDisplayList()[0];
  62992. if (!(el && el.useHoverLayer)) {
  62993. api.dispatchAction({
  62994. type: 'downplay',
  62995. seriesName: seriesName,
  62996. name: dataName,
  62997. excludeSeriesId: excludeSeriesId
  62998. });
  62999. }
  63000. }
  63001. /*
  63002. * Licensed to the Apache Software Foundation (ASF) under one
  63003. * or more contributor license agreements. See the NOTICE file
  63004. * distributed with this work for additional information
  63005. * regarding copyright ownership. The ASF licenses this file
  63006. * to you under the Apache License, Version 2.0 (the
  63007. * "License"); you may not use this file except in compliance
  63008. * with the License. You may obtain a copy of the License at
  63009. *
  63010. * http://www.apache.org/licenses/LICENSE-2.0
  63011. *
  63012. * Unless required by applicable law or agreed to in writing,
  63013. * software distributed under the License is distributed on an
  63014. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63015. * KIND, either express or implied. See the License for the
  63016. * specific language governing permissions and limitations
  63017. * under the License.
  63018. */
  63019. var legendFilter = function (ecModel) {
  63020. var legendModels = ecModel.findComponents({
  63021. mainType: 'legend'
  63022. });
  63023. if (legendModels && legendModels.length) {
  63024. ecModel.filterSeries(function (series) {
  63025. // If in any legend component the status is not selected.
  63026. // Because in legend series is assumed selected when it is not in the legend data.
  63027. for (var i = 0; i < legendModels.length; i++) {
  63028. if (!legendModels[i].isSelected(series.name)) {
  63029. return false;
  63030. }
  63031. }
  63032. return true;
  63033. });
  63034. }
  63035. };
  63036. /*
  63037. * Licensed to the Apache Software Foundation (ASF) under one
  63038. * or more contributor license agreements. See the NOTICE file
  63039. * distributed with this work for additional information
  63040. * regarding copyright ownership. The ASF licenses this file
  63041. * to you under the Apache License, Version 2.0 (the
  63042. * "License"); you may not use this file except in compliance
  63043. * with the License. You may obtain a copy of the License at
  63044. *
  63045. * http://www.apache.org/licenses/LICENSE-2.0
  63046. *
  63047. * Unless required by applicable law or agreed to in writing,
  63048. * software distributed under the License is distributed on an
  63049. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63050. * KIND, either express or implied. See the License for the
  63051. * specific language governing permissions and limitations
  63052. * under the License.
  63053. */
  63054. // Do not contain scrollable legend, for sake of file size.
  63055. // Series Filter
  63056. registerProcessor(legendFilter);
  63057. ComponentModel.registerSubTypeDefaulter('legend', function () {
  63058. // Default 'plain' when no type specified.
  63059. return 'plain';
  63060. });
  63061. /*
  63062. * Licensed to the Apache Software Foundation (ASF) under one
  63063. * or more contributor license agreements. See the NOTICE file
  63064. * distributed with this work for additional information
  63065. * regarding copyright ownership. The ASF licenses this file
  63066. * to you under the Apache License, Version 2.0 (the
  63067. * "License"); you may not use this file except in compliance
  63068. * with the License. You may obtain a copy of the License at
  63069. *
  63070. * http://www.apache.org/licenses/LICENSE-2.0
  63071. *
  63072. * Unless required by applicable law or agreed to in writing,
  63073. * software distributed under the License is distributed on an
  63074. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63075. * KIND, either express or implied. See the License for the
  63076. * specific language governing permissions and limitations
  63077. * under the License.
  63078. */
  63079. var ScrollableLegendModel = LegendModel.extend({
  63080. type: 'legend.scroll',
  63081. /**
  63082. * @param {number} scrollDataIndex
  63083. */
  63084. setScrollDataIndex: function (scrollDataIndex) {
  63085. this.option.scrollDataIndex = scrollDataIndex;
  63086. },
  63087. defaultOption: {
  63088. scrollDataIndex: 0,
  63089. pageButtonItemGap: 5,
  63090. pageButtonGap: null,
  63091. pageButtonPosition: 'end', // 'start' or 'end'
  63092. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  63093. pageIcons: {
  63094. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  63095. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  63096. },
  63097. pageIconColor: '#2f4554',
  63098. pageIconInactiveColor: '#aaa',
  63099. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  63100. pageTextStyle: {
  63101. color: '#333'
  63102. },
  63103. animationDurationUpdate: 800
  63104. },
  63105. /**
  63106. * @override
  63107. */
  63108. init: function (option, parentModel, ecModel, extraOpt) {
  63109. var inputPositionParams = getLayoutParams(option);
  63110. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  63111. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  63112. },
  63113. /**
  63114. * @override
  63115. */
  63116. mergeOption: function (option, extraOpt) {
  63117. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  63118. mergeAndNormalizeLayoutParams(this, this.option, option);
  63119. },
  63120. getOrient: function () {
  63121. return this.get('orient') === 'vertical'
  63122. ? {index: 1, name: 'vertical'}
  63123. : {index: 0, name: 'horizontal'};
  63124. }
  63125. });
  63126. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  63127. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  63128. var orient = legendModel.getOrient();
  63129. var ignoreSize = [1, 1];
  63130. ignoreSize[orient.index] = 0;
  63131. mergeLayoutParam(target, raw, {
  63132. type: 'box', ignoreSize: ignoreSize
  63133. });
  63134. }
  63135. /*
  63136. * Licensed to the Apache Software Foundation (ASF) under one
  63137. * or more contributor license agreements. See the NOTICE file
  63138. * distributed with this work for additional information
  63139. * regarding copyright ownership. The ASF licenses this file
  63140. * to you under the Apache License, Version 2.0 (the
  63141. * "License"); you may not use this file except in compliance
  63142. * with the License. You may obtain a copy of the License at
  63143. *
  63144. * http://www.apache.org/licenses/LICENSE-2.0
  63145. *
  63146. * Unless required by applicable law or agreed to in writing,
  63147. * software distributed under the License is distributed on an
  63148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63149. * KIND, either express or implied. See the License for the
  63150. * specific language governing permissions and limitations
  63151. * under the License.
  63152. */
  63153. /**
  63154. * Separate legend and scrollable legend to reduce package size.
  63155. */
  63156. var Group$4 = Group;
  63157. var WH$1 = ['width', 'height'];
  63158. var XY$1 = ['x', 'y'];
  63159. var ScrollableLegendView = LegendView.extend({
  63160. type: 'legend.scroll',
  63161. newlineDisabled: true,
  63162. init: function () {
  63163. ScrollableLegendView.superCall(this, 'init');
  63164. /**
  63165. * @private
  63166. * @type {number} For `scroll`.
  63167. */
  63168. this._currentIndex = 0;
  63169. /**
  63170. * @private
  63171. * @type {module:zrender/container/Group}
  63172. */
  63173. this.group.add(this._containerGroup = new Group$4());
  63174. this._containerGroup.add(this.getContentGroup());
  63175. /**
  63176. * @private
  63177. * @type {module:zrender/container/Group}
  63178. */
  63179. this.group.add(this._controllerGroup = new Group$4());
  63180. /**
  63181. *
  63182. * @private
  63183. */
  63184. this._showController;
  63185. },
  63186. /**
  63187. * @override
  63188. */
  63189. resetInner: function () {
  63190. ScrollableLegendView.superCall(this, 'resetInner');
  63191. this._controllerGroup.removeAll();
  63192. this._containerGroup.removeClipPath();
  63193. this._containerGroup.__rectSize = null;
  63194. },
  63195. /**
  63196. * @override
  63197. */
  63198. renderInner: function (itemAlign, legendModel, ecModel, api) {
  63199. var me = this;
  63200. // Render content items.
  63201. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  63202. var controllerGroup = this._controllerGroup;
  63203. // FIXME: support be 'auto' adapt to size number text length,
  63204. // e.g., '3/12345' should not overlap with the control arrow button.
  63205. var pageIconSize = legendModel.get('pageIconSize', true);
  63206. if (!isArray(pageIconSize)) {
  63207. pageIconSize = [pageIconSize, pageIconSize];
  63208. }
  63209. createPageButton('pagePrev', 0);
  63210. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  63211. controllerGroup.add(new Text({
  63212. name: 'pageText',
  63213. style: {
  63214. textFill: pageTextStyleModel.getTextColor(),
  63215. font: pageTextStyleModel.getFont(),
  63216. textVerticalAlign: 'middle',
  63217. textAlign: 'center'
  63218. },
  63219. silent: true
  63220. }));
  63221. createPageButton('pageNext', 1);
  63222. function createPageButton(name, iconIdx) {
  63223. var pageDataIndexName = name + 'DataIndex';
  63224. var icon = createIcon(
  63225. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  63226. {
  63227. // Buttons will be created in each render, so we do not need
  63228. // to worry about avoiding using legendModel kept in scope.
  63229. onclick: bind(
  63230. me._pageGo, me, pageDataIndexName, legendModel, api
  63231. )
  63232. },
  63233. {
  63234. x: -pageIconSize[0] / 2,
  63235. y: -pageIconSize[1] / 2,
  63236. width: pageIconSize[0],
  63237. height: pageIconSize[1]
  63238. }
  63239. );
  63240. icon.name = name;
  63241. controllerGroup.add(icon);
  63242. }
  63243. },
  63244. /**
  63245. * @override
  63246. */
  63247. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender) {
  63248. var contentGroup = this.getContentGroup();
  63249. var containerGroup = this._containerGroup;
  63250. var controllerGroup = this._controllerGroup;
  63251. var orientIdx = legendModel.getOrient().index;
  63252. var wh = WH$1[orientIdx];
  63253. var hw = WH$1[1 - orientIdx];
  63254. var yx = XY$1[1 - orientIdx];
  63255. // Place items in contentGroup.
  63256. box(
  63257. legendModel.get('orient'),
  63258. contentGroup,
  63259. legendModel.get('itemGap'),
  63260. !orientIdx ? null : maxSize.width,
  63261. orientIdx ? null : maxSize.height
  63262. );
  63263. box(
  63264. // Buttons in controller are layout always horizontally.
  63265. 'horizontal',
  63266. controllerGroup,
  63267. legendModel.get('pageButtonItemGap', true)
  63268. );
  63269. var contentRect = contentGroup.getBoundingRect();
  63270. var controllerRect = controllerGroup.getBoundingRect();
  63271. var showController = this._showController = contentRect[wh] > maxSize[wh];
  63272. var contentPos = [-contentRect.x, -contentRect.y];
  63273. // Remain contentPos when scroll animation perfroming.
  63274. // If first rendering, `contentGroup.position` is [0, 0], which
  63275. // does not make sense and may cause unexepcted animation if adopted.
  63276. if (!isFirstRender) {
  63277. contentPos[orientIdx] = contentGroup.position[orientIdx];
  63278. }
  63279. // Layout container group based on 0.
  63280. var containerPos = [0, 0];
  63281. var controllerPos = [-controllerRect.x, -controllerRect.y];
  63282. var pageButtonGap = retrieve2(
  63283. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  63284. );
  63285. // Place containerGroup and controllerGroup and contentGroup.
  63286. if (showController) {
  63287. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  63288. // controller is on the right / bottom.
  63289. if (pageButtonPosition === 'end') {
  63290. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  63291. }
  63292. // controller is on the left / top.
  63293. else {
  63294. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  63295. }
  63296. }
  63297. // Always align controller to content as 'middle'.
  63298. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  63299. contentGroup.attr('position', contentPos);
  63300. containerGroup.attr('position', containerPos);
  63301. controllerGroup.attr('position', controllerPos);
  63302. // Calculate `mainRect` and set `clipPath`.
  63303. // mainRect should not be calculated by `this.group.getBoundingRect()`
  63304. // for sake of the overflow.
  63305. var mainRect = this.group.getBoundingRect();
  63306. var mainRect = {x: 0, y: 0};
  63307. // Consider content may be overflow (should be clipped).
  63308. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  63309. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  63310. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  63311. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  63312. containerGroup.__rectSize = maxSize[wh];
  63313. if (showController) {
  63314. var clipShape = {x: 0, y: 0};
  63315. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  63316. clipShape[hw] = mainRect[hw];
  63317. containerGroup.setClipPath(new Rect({shape: clipShape}));
  63318. // Consider content may be larger than container, container rect
  63319. // can not be obtained from `containerGroup.getBoundingRect()`.
  63320. containerGroup.__rectSize = clipShape[wh];
  63321. }
  63322. else {
  63323. // Do not remove or ignore controller. Keep them set as place holders.
  63324. controllerGroup.eachChild(function (child) {
  63325. child.attr({invisible: true, silent: true});
  63326. });
  63327. }
  63328. // Content translate animation.
  63329. var pageInfo = this._getPageInfo(legendModel);
  63330. pageInfo.pageIndex != null && updateProps(
  63331. contentGroup,
  63332. {position: pageInfo.contentPosition},
  63333. // When switch from "show controller" to "not show controller", view should be
  63334. // updated immediately without animation, otherwise causes weird efffect.
  63335. showController ? legendModel : false
  63336. );
  63337. this._updatePageInfoView(legendModel, pageInfo);
  63338. return mainRect;
  63339. },
  63340. _pageGo: function (to, legendModel, api) {
  63341. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  63342. scrollDataIndex != null && api.dispatchAction({
  63343. type: 'legendScroll',
  63344. scrollDataIndex: scrollDataIndex,
  63345. legendId: legendModel.id
  63346. });
  63347. },
  63348. _updatePageInfoView: function (legendModel, pageInfo) {
  63349. var controllerGroup = this._controllerGroup;
  63350. each$1(['pagePrev', 'pageNext'], function (name) {
  63351. var canJump = pageInfo[name + 'DataIndex'] != null;
  63352. var icon = controllerGroup.childOfName(name);
  63353. if (icon) {
  63354. icon.setStyle(
  63355. 'fill',
  63356. canJump
  63357. ? legendModel.get('pageIconColor', true)
  63358. : legendModel.get('pageIconInactiveColor', true)
  63359. );
  63360. icon.cursor = canJump ? 'pointer' : 'default';
  63361. }
  63362. });
  63363. var pageText = controllerGroup.childOfName('pageText');
  63364. var pageFormatter = legendModel.get('pageFormatter');
  63365. var pageIndex = pageInfo.pageIndex;
  63366. var current = pageIndex != null ? pageIndex + 1 : 0;
  63367. var total = pageInfo.pageCount;
  63368. pageText && pageFormatter && pageText.setStyle(
  63369. 'text',
  63370. isString(pageFormatter)
  63371. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  63372. : pageFormatter({current: current, total: total})
  63373. );
  63374. },
  63375. /**
  63376. * @param {module:echarts/model/Model} legendModel
  63377. * @return {Object} {
  63378. * contentPosition: Array.<number>, null when data item not found.
  63379. * pageIndex: number, null when data item not found.
  63380. * pageCount: number, always be a number, can be 0.
  63381. * pagePrevDataIndex: number, null when no next page.
  63382. * pageNextDataIndex: number, null when no previous page.
  63383. * }
  63384. */
  63385. _getPageInfo: function (legendModel) {
  63386. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  63387. var contentGroup = this.getContentGroup();
  63388. var containerRectSize = this._containerGroup.__rectSize;
  63389. var orientIdx = legendModel.getOrient().index;
  63390. var wh = WH$1[orientIdx];
  63391. var xy = XY$1[orientIdx];
  63392. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  63393. var children = contentGroup.children();
  63394. var targetItem = children[targetItemIndex];
  63395. var itemCount = children.length;
  63396. var pCount = !itemCount ? 0 : 1;
  63397. var result = {
  63398. contentPosition: contentGroup.position.slice(),
  63399. pageCount: pCount,
  63400. pageIndex: pCount - 1,
  63401. pagePrevDataIndex: null,
  63402. pageNextDataIndex: null
  63403. };
  63404. if (!targetItem) {
  63405. return result;
  63406. }
  63407. var targetItemInfo = getItemInfo(targetItem);
  63408. result.contentPosition[orientIdx] = -targetItemInfo.s;
  63409. // Strategy:
  63410. // (1) Always align based on the left/top most item.
  63411. // (2) It is user-friendly that the last item shown in the
  63412. // current window is shown at the begining of next window.
  63413. // Otherwise if half of the last item is cut by the window,
  63414. // it will have no chance to display entirely.
  63415. // (3) Consider that item size probably be different, we
  63416. // have calculate pageIndex by size rather than item index,
  63417. // and we can not get page index directly by division.
  63418. // (4) The window is to narrow to contain more than
  63419. // one item, we should make sure that the page can be fliped.
  63420. for (var i = targetItemIndex + 1,
  63421. winStartItemInfo = targetItemInfo,
  63422. winEndItemInfo = targetItemInfo,
  63423. currItemInfo = null;
  63424. i <= itemCount;
  63425. ++i
  63426. ) {
  63427. currItemInfo = getItemInfo(children[i]);
  63428. if (
  63429. // Half of the last item is out of the window.
  63430. (!currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize)
  63431. // If the current item does not intersect with the window, the new page
  63432. // can be started at the current item or the last item.
  63433. || (currItemInfo && !intersect(currItemInfo, winStartItemInfo.s))
  63434. ) {
  63435. if (winEndItemInfo.i > winStartItemInfo.i) {
  63436. winStartItemInfo = winEndItemInfo;
  63437. }
  63438. else { // e.g., when page size is smaller than item size.
  63439. winStartItemInfo = currItemInfo;
  63440. }
  63441. if (winStartItemInfo) {
  63442. if (result.pageNextDataIndex == null) {
  63443. result.pageNextDataIndex = winStartItemInfo.i;
  63444. }
  63445. ++result.pageCount;
  63446. }
  63447. }
  63448. winEndItemInfo = currItemInfo;
  63449. }
  63450. for (var i = targetItemIndex - 1,
  63451. winStartItemInfo = targetItemInfo,
  63452. winEndItemInfo = targetItemInfo,
  63453. currItemInfo = null;
  63454. i >= -1;
  63455. --i
  63456. ) {
  63457. currItemInfo = getItemInfo(children[i]);
  63458. if (
  63459. // If the the end item does not intersect with the window started
  63460. // from the current item, a page can be settled.
  63461. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s))
  63462. // e.g., when page size is smaller than item size.
  63463. && winStartItemInfo.i < winEndItemInfo.i
  63464. ) {
  63465. winEndItemInfo = winStartItemInfo;
  63466. if (result.pagePrevDataIndex == null) {
  63467. result.pagePrevDataIndex = winStartItemInfo.i;
  63468. }
  63469. ++result.pageCount;
  63470. ++result.pageIndex;
  63471. }
  63472. winStartItemInfo = currItemInfo;
  63473. }
  63474. return result;
  63475. function getItemInfo(el) {
  63476. if (el) {
  63477. var itemRect = el.getBoundingRect();
  63478. var start = itemRect[xy] + el.position[orientIdx];
  63479. return {
  63480. s: start,
  63481. e: start + itemRect[wh],
  63482. i: el.__legendDataIndex
  63483. };
  63484. }
  63485. }
  63486. function intersect(itemInfo, winStart) {
  63487. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  63488. }
  63489. },
  63490. _findTargetItemIndex: function (targetDataIndex) {
  63491. var index;
  63492. var contentGroup = this.getContentGroup();
  63493. if (this._showController) {
  63494. contentGroup.eachChild(function (child, idx) {
  63495. if (child.__legendDataIndex === targetDataIndex) {
  63496. index = idx;
  63497. }
  63498. });
  63499. }
  63500. else {
  63501. index = 0;
  63502. }
  63503. return index;
  63504. }
  63505. });
  63506. /*
  63507. * Licensed to the Apache Software Foundation (ASF) under one
  63508. * or more contributor license agreements. See the NOTICE file
  63509. * distributed with this work for additional information
  63510. * regarding copyright ownership. The ASF licenses this file
  63511. * to you under the Apache License, Version 2.0 (the
  63512. * "License"); you may not use this file except in compliance
  63513. * with the License. You may obtain a copy of the License at
  63514. *
  63515. * http://www.apache.org/licenses/LICENSE-2.0
  63516. *
  63517. * Unless required by applicable law or agreed to in writing,
  63518. * software distributed under the License is distributed on an
  63519. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63520. * KIND, either express or implied. See the License for the
  63521. * specific language governing permissions and limitations
  63522. * under the License.
  63523. */
  63524. /**
  63525. * @event legendScroll
  63526. * @type {Object}
  63527. * @property {string} type 'legendScroll'
  63528. * @property {string} scrollDataIndex
  63529. */
  63530. registerAction(
  63531. 'legendScroll', 'legendscroll',
  63532. function (payload, ecModel) {
  63533. var scrollDataIndex = payload.scrollDataIndex;
  63534. scrollDataIndex != null && ecModel.eachComponent(
  63535. {mainType: 'legend', subType: 'scroll', query: payload},
  63536. function (legendModel) {
  63537. legendModel.setScrollDataIndex(scrollDataIndex);
  63538. }
  63539. );
  63540. }
  63541. );
  63542. /*
  63543. * Licensed to the Apache Software Foundation (ASF) under one
  63544. * or more contributor license agreements. See the NOTICE file
  63545. * distributed with this work for additional information
  63546. * regarding copyright ownership. The ASF licenses this file
  63547. * to you under the Apache License, Version 2.0 (the
  63548. * "License"); you may not use this file except in compliance
  63549. * with the License. You may obtain a copy of the License at
  63550. *
  63551. * http://www.apache.org/licenses/LICENSE-2.0
  63552. *
  63553. * Unless required by applicable law or agreed to in writing,
  63554. * software distributed under the License is distributed on an
  63555. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63556. * KIND, either express or implied. See the License for the
  63557. * specific language governing permissions and limitations
  63558. * under the License.
  63559. */
  63560. /**
  63561. * Legend component entry file8
  63562. */
  63563. /*
  63564. * Licensed to the Apache Software Foundation (ASF) under one
  63565. * or more contributor license agreements. See the NOTICE file
  63566. * distributed with this work for additional information
  63567. * regarding copyright ownership. The ASF licenses this file
  63568. * to you under the Apache License, Version 2.0 (the
  63569. * "License"); you may not use this file except in compliance
  63570. * with the License. You may obtain a copy of the License at
  63571. *
  63572. * http://www.apache.org/licenses/LICENSE-2.0
  63573. *
  63574. * Unless required by applicable law or agreed to in writing,
  63575. * software distributed under the License is distributed on an
  63576. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63577. * KIND, either express or implied. See the License for the
  63578. * specific language governing permissions and limitations
  63579. * under the License.
  63580. */
  63581. extendComponentModel({
  63582. type: 'tooltip',
  63583. dependencies: ['axisPointer'],
  63584. defaultOption: {
  63585. zlevel: 0,
  63586. z: 60,
  63587. show: true,
  63588. // tooltip主体内容
  63589. showContent: true,
  63590. // 'trigger' only works on coordinate system.
  63591. // 'item' | 'axis' | 'none'
  63592. trigger: 'item',
  63593. // 'click' | 'mousemove' | 'none'
  63594. triggerOn: 'mousemove|click',
  63595. alwaysShowContent: false,
  63596. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  63597. renderMode: 'auto', // 'auto' | 'html' | 'richText'
  63598. // 'auto': use html by default, and use non-html if `document` is not defined
  63599. // 'html': use html for tooltip
  63600. // 'richText': use canvas, svg, and etc. for tooltip
  63601. // 位置 {Array} | {Function}
  63602. // position: null
  63603. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  63604. // align: null,
  63605. // verticalAlign: null,
  63606. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  63607. confine: false,
  63608. // 内容格式器:{string}(Template) ¦ {Function}
  63609. // formatter: null
  63610. showDelay: 0,
  63611. // 隐藏延迟,单位ms
  63612. hideDelay: 100,
  63613. // 动画变换时间,单位s
  63614. transitionDuration: 0.4,
  63615. enterable: false,
  63616. // 提示背景颜色,默认为透明度为0.7的黑色
  63617. backgroundColor: 'rgba(50,50,50,0.7)',
  63618. // 提示边框颜色
  63619. borderColor: '#333',
  63620. // 提示边框圆角,单位px,默认为4
  63621. borderRadius: 4,
  63622. // 提示边框线宽,单位px,默认为0(无边框)
  63623. borderWidth: 0,
  63624. // 提示内边距,单位px,默认各方向内边距为5,
  63625. // 接受数组分别设定上右下左边距,同css
  63626. padding: 5,
  63627. // Extra css text
  63628. extraCssText: '',
  63629. // 坐标轴指示器,坐标轴触发有效
  63630. axisPointer: {
  63631. // 默认为直线
  63632. // 可选为:'line' | 'shadow' | 'cross'
  63633. type: 'line',
  63634. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  63635. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  63636. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  63637. // 极坐标系会默认选择 angle 轴
  63638. axis: 'auto',
  63639. animation: 'auto',
  63640. animationDurationUpdate: 200,
  63641. animationEasingUpdate: 'exponentialOut',
  63642. crossStyle: {
  63643. color: '#999',
  63644. width: 1,
  63645. type: 'dashed',
  63646. // TODO formatter
  63647. textStyle: {}
  63648. }
  63649. // lineStyle and shadowStyle should not be specified here,
  63650. // otherwise it will always override those styles on option.axisPointer.
  63651. },
  63652. textStyle: {
  63653. color: '#fff',
  63654. fontSize: 14
  63655. }
  63656. }
  63657. });
  63658. /*
  63659. * Licensed to the Apache Software Foundation (ASF) under one
  63660. * or more contributor license agreements. See the NOTICE file
  63661. * distributed with this work for additional information
  63662. * regarding copyright ownership. The ASF licenses this file
  63663. * to you under the Apache License, Version 2.0 (the
  63664. * "License"); you may not use this file except in compliance
  63665. * with the License. You may obtain a copy of the License at
  63666. *
  63667. * http://www.apache.org/licenses/LICENSE-2.0
  63668. *
  63669. * Unless required by applicable law or agreed to in writing,
  63670. * software distributed under the License is distributed on an
  63671. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63672. * KIND, either express or implied. See the License for the
  63673. * specific language governing permissions and limitations
  63674. * under the License.
  63675. */
  63676. var each$18 = each$1;
  63677. var toCamelCase$1 = toCamelCase;
  63678. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  63679. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  63680. /**
  63681. * @param {number} duration
  63682. * @return {string}
  63683. * @inner
  63684. */
  63685. function assembleTransition(duration) {
  63686. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  63687. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  63688. + 'top ' + duration + 's ' + transitionCurve;
  63689. return map(vendors, function (vendorPrefix) {
  63690. return vendorPrefix + 'transition:' + transitionText;
  63691. }).join(';');
  63692. }
  63693. /**
  63694. * @param {Object} textStyle
  63695. * @return {string}
  63696. * @inner
  63697. */
  63698. function assembleFont(textStyleModel) {
  63699. var cssText = [];
  63700. var fontSize = textStyleModel.get('fontSize');
  63701. var color = textStyleModel.getTextColor();
  63702. color && cssText.push('color:' + color);
  63703. cssText.push('font:' + textStyleModel.getFont());
  63704. fontSize
  63705. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  63706. each$18(['decoration', 'align'], function (name) {
  63707. var val = textStyleModel.get(name);
  63708. val && cssText.push('text-' + name + ':' + val);
  63709. });
  63710. return cssText.join(';');
  63711. }
  63712. /**
  63713. * @param {Object} tooltipModel
  63714. * @return {string}
  63715. * @inner
  63716. */
  63717. function assembleCssText(tooltipModel) {
  63718. var cssText = [];
  63719. var transitionDuration = tooltipModel.get('transitionDuration');
  63720. var backgroundColor = tooltipModel.get('backgroundColor');
  63721. var textStyleModel = tooltipModel.getModel('textStyle');
  63722. var padding = tooltipModel.get('padding');
  63723. // Animation transition. Do not animate when transitionDuration is 0.
  63724. transitionDuration
  63725. && cssText.push(assembleTransition(transitionDuration));
  63726. if (backgroundColor) {
  63727. if (env$1.canvasSupported) {
  63728. cssText.push('background-Color:' + backgroundColor);
  63729. }
  63730. else {
  63731. // for ie
  63732. cssText.push(
  63733. 'background-Color:#' + toHex(backgroundColor)
  63734. );
  63735. cssText.push('filter:alpha(opacity=70)');
  63736. }
  63737. }
  63738. // Border style
  63739. each$18(['width', 'color', 'radius'], function (name) {
  63740. var borderName = 'border-' + name;
  63741. var camelCase = toCamelCase$1(borderName);
  63742. var val = tooltipModel.get(camelCase);
  63743. val != null
  63744. && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  63745. });
  63746. // Text style
  63747. cssText.push(assembleFont(textStyleModel));
  63748. // Padding
  63749. if (padding != null) {
  63750. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  63751. }
  63752. return cssText.join(';') + ';';
  63753. }
  63754. /**
  63755. * @alias module:echarts/component/tooltip/TooltipContent
  63756. * @constructor
  63757. */
  63758. function TooltipContent(container, api) {
  63759. if (env$1.wxa) {
  63760. return null;
  63761. }
  63762. var el = document.createElement('div');
  63763. var zr = this._zr = api.getZr();
  63764. this.el = el;
  63765. this._x = api.getWidth() / 2;
  63766. this._y = api.getHeight() / 2;
  63767. container.appendChild(el);
  63768. this._container = container;
  63769. this._show = false;
  63770. /**
  63771. * @private
  63772. */
  63773. this._hideTimeout;
  63774. var self = this;
  63775. el.onmouseenter = function () {
  63776. // clear the timeout in hideLater and keep showing tooltip
  63777. if (self._enterable) {
  63778. clearTimeout(self._hideTimeout);
  63779. self._show = true;
  63780. }
  63781. self._inContent = true;
  63782. };
  63783. el.onmousemove = function (e) {
  63784. e = e || window.event;
  63785. if (!self._enterable) {
  63786. // Try trigger zrender event to avoid mouse
  63787. // in and out shape too frequently
  63788. var handler = zr.handler;
  63789. normalizeEvent(container, e, true);
  63790. handler.dispatch('mousemove', e);
  63791. }
  63792. };
  63793. el.onmouseleave = function () {
  63794. if (self._enterable) {
  63795. if (self._show) {
  63796. self.hideLater(self._hideDelay);
  63797. }
  63798. }
  63799. self._inContent = false;
  63800. };
  63801. }
  63802. TooltipContent.prototype = {
  63803. constructor: TooltipContent,
  63804. /**
  63805. * @private
  63806. * @type {boolean}
  63807. */
  63808. _enterable: true,
  63809. /**
  63810. * Update when tooltip is rendered
  63811. */
  63812. update: function () {
  63813. // FIXME
  63814. // Move this logic to ec main?
  63815. var container = this._container;
  63816. var stl = container.currentStyle
  63817. || document.defaultView.getComputedStyle(container);
  63818. var domStyle = container.style;
  63819. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  63820. domStyle.position = 'relative';
  63821. }
  63822. // Hide the tooltip
  63823. // PENDING
  63824. // this.hide();
  63825. },
  63826. show: function (tooltipModel) {
  63827. clearTimeout(this._hideTimeout);
  63828. var el = this.el;
  63829. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  63830. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  63831. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  63832. + (tooltipModel.get('extraCssText') || '');
  63833. el.style.display = el.innerHTML ? 'block' : 'none';
  63834. // If mouse occsionally move over the tooltip, a mouseout event will be
  63835. // triggered by canvas, and cuase some unexpectable result like dragging
  63836. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  63837. // it. Although it is not suppored by IE8~IE10, fortunately it is a rare
  63838. // scenario.
  63839. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  63840. this._show = true;
  63841. },
  63842. setContent: function (content) {
  63843. this.el.innerHTML = content == null ? '' : content;
  63844. },
  63845. setEnterable: function (enterable) {
  63846. this._enterable = enterable;
  63847. },
  63848. getSize: function () {
  63849. var el = this.el;
  63850. return [el.clientWidth, el.clientHeight];
  63851. },
  63852. moveTo: function (x, y) {
  63853. // xy should be based on canvas root. But tooltipContent is
  63854. // the sibling of canvas root. So padding of ec container
  63855. // should be considered here.
  63856. var zr = this._zr;
  63857. var viewportRootOffset;
  63858. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  63859. x += viewportRootOffset.offsetLeft;
  63860. y += viewportRootOffset.offsetTop;
  63861. }
  63862. var style = this.el.style;
  63863. style.left = x + 'px';
  63864. style.top = y + 'px';
  63865. this._x = x;
  63866. this._y = y;
  63867. },
  63868. hide: function () {
  63869. this.el.style.display = 'none';
  63870. this._show = false;
  63871. },
  63872. hideLater: function (time) {
  63873. if (this._show && !(this._inContent && this._enterable)) {
  63874. if (time) {
  63875. this._hideDelay = time;
  63876. // Set show false to avoid invoke hideLater mutiple times
  63877. this._show = false;
  63878. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  63879. }
  63880. else {
  63881. this.hide();
  63882. }
  63883. }
  63884. },
  63885. isShow: function () {
  63886. return this._show;
  63887. },
  63888. getOuterSize: function () {
  63889. var width = this.el.clientWidth;
  63890. var height = this.el.clientHeight;
  63891. // Consider browser compatibility.
  63892. // IE8 does not support getComputedStyle.
  63893. if (document.defaultView && document.defaultView.getComputedStyle) {
  63894. var stl = document.defaultView.getComputedStyle(this.el);
  63895. if (stl) {
  63896. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  63897. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  63898. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  63899. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  63900. }
  63901. }
  63902. return {width: width, height: height};
  63903. }
  63904. };
  63905. /*
  63906. * Licensed to the Apache Software Foundation (ASF) under one
  63907. * or more contributor license agreements. See the NOTICE file
  63908. * distributed with this work for additional information
  63909. * regarding copyright ownership. The ASF licenses this file
  63910. * to you under the Apache License, Version 2.0 (the
  63911. * "License"); you may not use this file except in compliance
  63912. * with the License. You may obtain a copy of the License at
  63913. *
  63914. * http://www.apache.org/licenses/LICENSE-2.0
  63915. *
  63916. * Unless required by applicable law or agreed to in writing,
  63917. * software distributed under the License is distributed on an
  63918. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63919. * KIND, either express or implied. See the License for the
  63920. * specific language governing permissions and limitations
  63921. * under the License.
  63922. */
  63923. // import Group from 'zrender/src/container/Group';
  63924. /**
  63925. * @alias module:echarts/component/tooltip/TooltipRichContent
  63926. * @constructor
  63927. */
  63928. function TooltipRichContent(api) {
  63929. this._zr = api.getZr();
  63930. this._show = false;
  63931. /**
  63932. * @private
  63933. */
  63934. this._hideTimeout;
  63935. }
  63936. TooltipRichContent.prototype = {
  63937. constructor: TooltipRichContent,
  63938. /**
  63939. * @private
  63940. * @type {boolean}
  63941. */
  63942. _enterable: true,
  63943. /**
  63944. * Update when tooltip is rendered
  63945. */
  63946. update: function () {
  63947. // noop
  63948. },
  63949. show: function (tooltipModel) {
  63950. if (this._hideTimeout) {
  63951. clearTimeout(this._hideTimeout);
  63952. }
  63953. this.el.attr('show', true);
  63954. this._show = true;
  63955. },
  63956. /**
  63957. * Set tooltip content
  63958. *
  63959. * @param {string} content rich text string of content
  63960. * @param {Object} markerRich rich text style
  63961. * @param {Object} tooltipModel tooltip model
  63962. */
  63963. setContent: function (content, markerRich, tooltipModel) {
  63964. if (this.el) {
  63965. this._zr.remove(this.el);
  63966. }
  63967. var markers = {};
  63968. var text = content;
  63969. var prefix = '{marker';
  63970. var suffix = '|}';
  63971. var startId = text.indexOf(prefix);
  63972. while (startId >= 0) {
  63973. var endId = text.indexOf(suffix);
  63974. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  63975. if (name.indexOf('sub') > -1) {
  63976. markers['marker' + name] = {
  63977. textWidth: 4,
  63978. textHeight: 4,
  63979. textBorderRadius: 2,
  63980. textBackgroundColor: markerRich[name],
  63981. // TODO: textOffset is not implemented for rich text
  63982. textOffset: [3, 0]
  63983. };
  63984. }
  63985. else {
  63986. markers['marker' + name] = {
  63987. textWidth: 10,
  63988. textHeight: 10,
  63989. textBorderRadius: 5,
  63990. textBackgroundColor: markerRich[name]
  63991. };
  63992. }
  63993. text = text.substr(endId + 1);
  63994. startId = text.indexOf('{marker');
  63995. }
  63996. this.el = new Text({
  63997. style: {
  63998. rich: markers,
  63999. text: content,
  64000. textLineHeight: 20,
  64001. textBackgroundColor: tooltipModel.get('backgroundColor'),
  64002. textBorderRadius: tooltipModel.get('borderRadius'),
  64003. textFill: tooltipModel.get('textStyle.color'),
  64004. textPadding: tooltipModel.get('padding')
  64005. },
  64006. z: tooltipModel.get('z')
  64007. });
  64008. this._zr.add(this.el);
  64009. var self = this;
  64010. this.el.on('mouseover', function () {
  64011. // clear the timeout in hideLater and keep showing tooltip
  64012. if (self._enterable) {
  64013. clearTimeout(self._hideTimeout);
  64014. self._show = true;
  64015. }
  64016. self._inContent = true;
  64017. });
  64018. this.el.on('mouseout', function () {
  64019. if (self._enterable) {
  64020. if (self._show) {
  64021. self.hideLater(self._hideDelay);
  64022. }
  64023. }
  64024. self._inContent = false;
  64025. });
  64026. },
  64027. setEnterable: function (enterable) {
  64028. this._enterable = enterable;
  64029. },
  64030. getSize: function () {
  64031. var bounding = this.el.getBoundingRect();
  64032. return [bounding.width, bounding.height];
  64033. },
  64034. moveTo: function (x, y) {
  64035. if (this.el) {
  64036. this.el.attr('position', [x, y]);
  64037. }
  64038. },
  64039. hide: function () {
  64040. this.el.hide();
  64041. this._show = false;
  64042. },
  64043. hideLater: function (time) {
  64044. if (this._show && !(this._inContent && this._enterable)) {
  64045. if (time) {
  64046. this._hideDelay = time;
  64047. // Set show false to avoid invoke hideLater mutiple times
  64048. this._show = false;
  64049. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  64050. }
  64051. else {
  64052. this.hide();
  64053. }
  64054. }
  64055. },
  64056. isShow: function () {
  64057. return this._show;
  64058. },
  64059. getOuterSize: function () {
  64060. return this.getSize();
  64061. }
  64062. };
  64063. /*
  64064. * Licensed to the Apache Software Foundation (ASF) under one
  64065. * or more contributor license agreements. See the NOTICE file
  64066. * distributed with this work for additional information
  64067. * regarding copyright ownership. The ASF licenses this file
  64068. * to you under the Apache License, Version 2.0 (the
  64069. * "License"); you may not use this file except in compliance
  64070. * with the License. You may obtain a copy of the License at
  64071. *
  64072. * http://www.apache.org/licenses/LICENSE-2.0
  64073. *
  64074. * Unless required by applicable law or agreed to in writing,
  64075. * software distributed under the License is distributed on an
  64076. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64077. * KIND, either express or implied. See the License for the
  64078. * specific language governing permissions and limitations
  64079. * under the License.
  64080. */
  64081. var bind$3 = bind;
  64082. var each$17 = each$1;
  64083. var parsePercent$2 = parsePercent$1;
  64084. var proxyRect = new Rect({
  64085. shape: {x: -1, y: -1, width: 2, height: 2}
  64086. });
  64087. extendComponentView({
  64088. type: 'tooltip',
  64089. init: function (ecModel, api) {
  64090. if (env$1.node) {
  64091. return;
  64092. }
  64093. var tooltipModel = ecModel.getComponent('tooltip');
  64094. var renderMode = tooltipModel.get('renderMode');
  64095. this._renderMode = getTooltipRenderMode(renderMode);
  64096. var tooltipContent;
  64097. if (this._renderMode === 'html') {
  64098. tooltipContent = new TooltipContent(api.getDom(), api);
  64099. this._newLine = '<br/>';
  64100. }
  64101. else {
  64102. tooltipContent = new TooltipRichContent(api);
  64103. this._newLine = '\n';
  64104. }
  64105. this._tooltipContent = tooltipContent;
  64106. },
  64107. render: function (tooltipModel, ecModel, api) {
  64108. if (env$1.node) {
  64109. return;
  64110. }
  64111. // Reset
  64112. this.group.removeAll();
  64113. /**
  64114. * @private
  64115. * @type {module:echarts/component/tooltip/TooltipModel}
  64116. */
  64117. this._tooltipModel = tooltipModel;
  64118. /**
  64119. * @private
  64120. * @type {module:echarts/model/Global}
  64121. */
  64122. this._ecModel = ecModel;
  64123. /**
  64124. * @private
  64125. * @type {module:echarts/ExtensionAPI}
  64126. */
  64127. this._api = api;
  64128. /**
  64129. * Should be cleaned when render.
  64130. * @private
  64131. * @type {Array.<Array.<Object>>}
  64132. */
  64133. this._lastDataByCoordSys = null;
  64134. /**
  64135. * @private
  64136. * @type {boolean}
  64137. */
  64138. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  64139. var tooltipContent = this._tooltipContent;
  64140. tooltipContent.update();
  64141. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  64142. this._initGlobalListener();
  64143. this._keepShow();
  64144. },
  64145. _initGlobalListener: function () {
  64146. var tooltipModel = this._tooltipModel;
  64147. var triggerOn = tooltipModel.get('triggerOn');
  64148. register(
  64149. 'itemTooltip',
  64150. this._api,
  64151. bind$3(function (currTrigger, e, dispatchAction) {
  64152. // If 'none', it is not controlled by mouse totally.
  64153. if (triggerOn !== 'none') {
  64154. if (triggerOn.indexOf(currTrigger) >= 0) {
  64155. this._tryShow(e, dispatchAction);
  64156. }
  64157. else if (currTrigger === 'leave') {
  64158. this._hide(dispatchAction);
  64159. }
  64160. }
  64161. }, this)
  64162. );
  64163. },
  64164. _keepShow: function () {
  64165. var tooltipModel = this._tooltipModel;
  64166. var ecModel = this._ecModel;
  64167. var api = this._api;
  64168. // Try to keep the tooltip show when refreshing
  64169. if (this._lastX != null
  64170. && this._lastY != null
  64171. // When user is willing to control tooltip totally using API,
  64172. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  64173. // which is not expected.
  64174. && tooltipModel.get('triggerOn') !== 'none'
  64175. ) {
  64176. var self = this;
  64177. clearTimeout(this._refreshUpdateTimeout);
  64178. this._refreshUpdateTimeout = setTimeout(function () {
  64179. // Show tip next tick after other charts are rendered
  64180. // In case highlight action has wrong result
  64181. // FIXME
  64182. self.manuallyShowTip(tooltipModel, ecModel, api, {
  64183. x: self._lastX,
  64184. y: self._lastY
  64185. });
  64186. });
  64187. }
  64188. },
  64189. /**
  64190. * Show tip manually by
  64191. * dispatchAction({
  64192. * type: 'showTip',
  64193. * x: 10,
  64194. * y: 10
  64195. * });
  64196. * Or
  64197. * dispatchAction({
  64198. * type: 'showTip',
  64199. * seriesIndex: 0,
  64200. * dataIndex or dataIndexInside or name
  64201. * });
  64202. *
  64203. * TODO Batch
  64204. */
  64205. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  64206. if (payload.from === this.uid || env$1.node) {
  64207. return;
  64208. }
  64209. var dispatchAction = makeDispatchAction$1(payload, api);
  64210. // Reset ticket
  64211. this._ticket = '';
  64212. // When triggered from axisPointer.
  64213. var dataByCoordSys = payload.dataByCoordSys;
  64214. if (payload.tooltip && payload.x != null && payload.y != null) {
  64215. var el = proxyRect;
  64216. el.position = [payload.x, payload.y];
  64217. el.update();
  64218. el.tooltip = payload.tooltip;
  64219. // Manually show tooltip while view is not using zrender elements.
  64220. this._tryShow({
  64221. offsetX: payload.x,
  64222. offsetY: payload.y,
  64223. target: el
  64224. }, dispatchAction);
  64225. }
  64226. else if (dataByCoordSys) {
  64227. this._tryShow({
  64228. offsetX: payload.x,
  64229. offsetY: payload.y,
  64230. position: payload.position,
  64231. event: {},
  64232. dataByCoordSys: payload.dataByCoordSys,
  64233. tooltipOption: payload.tooltipOption
  64234. }, dispatchAction);
  64235. }
  64236. else if (payload.seriesIndex != null) {
  64237. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  64238. return;
  64239. }
  64240. var pointInfo = findPointFromSeries(payload, ecModel);
  64241. var cx = pointInfo.point[0];
  64242. var cy = pointInfo.point[1];
  64243. if (cx != null && cy != null) {
  64244. this._tryShow({
  64245. offsetX: cx,
  64246. offsetY: cy,
  64247. position: payload.position,
  64248. target: pointInfo.el,
  64249. event: {}
  64250. }, dispatchAction);
  64251. }
  64252. }
  64253. else if (payload.x != null && payload.y != null) {
  64254. // FIXME
  64255. // should wrap dispatchAction like `axisPointer/globalListener` ?
  64256. api.dispatchAction({
  64257. type: 'updateAxisPointer',
  64258. x: payload.x,
  64259. y: payload.y
  64260. });
  64261. this._tryShow({
  64262. offsetX: payload.x,
  64263. offsetY: payload.y,
  64264. position: payload.position,
  64265. target: api.getZr().findHover(payload.x, payload.y).target,
  64266. event: {}
  64267. }, dispatchAction);
  64268. }
  64269. },
  64270. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  64271. var tooltipContent = this._tooltipContent;
  64272. if (!this._alwaysShowContent && this._tooltipModel) {
  64273. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  64274. }
  64275. this._lastX = this._lastY = null;
  64276. if (payload.from !== this.uid) {
  64277. this._hide(makeDispatchAction$1(payload, api));
  64278. }
  64279. },
  64280. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  64281. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  64282. // and tooltip.
  64283. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  64284. var seriesIndex = payload.seriesIndex;
  64285. var dataIndex = payload.dataIndex;
  64286. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  64287. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  64288. return;
  64289. }
  64290. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  64291. if (!seriesModel) {
  64292. return;
  64293. }
  64294. var data = seriesModel.getData();
  64295. var tooltipModel = buildTooltipModel([
  64296. data.getItemModel(dataIndex),
  64297. seriesModel,
  64298. (seriesModel.coordinateSystem || {}).model,
  64299. tooltipModel
  64300. ]);
  64301. if (tooltipModel.get('trigger') !== 'axis') {
  64302. return;
  64303. }
  64304. api.dispatchAction({
  64305. type: 'updateAxisPointer',
  64306. seriesIndex: seriesIndex,
  64307. dataIndex: dataIndex,
  64308. position: payload.position
  64309. });
  64310. return true;
  64311. },
  64312. _tryShow: function (e, dispatchAction) {
  64313. var el = e.target;
  64314. var tooltipModel = this._tooltipModel;
  64315. if (!tooltipModel) {
  64316. return;
  64317. }
  64318. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  64319. this._lastX = e.offsetX;
  64320. this._lastY = e.offsetY;
  64321. var dataByCoordSys = e.dataByCoordSys;
  64322. if (dataByCoordSys && dataByCoordSys.length) {
  64323. this._showAxisTooltip(dataByCoordSys, e);
  64324. }
  64325. // Always show item tooltip if mouse is on the element with dataIndex
  64326. else if (el && el.dataIndex != null) {
  64327. this._lastDataByCoordSys = null;
  64328. this._showSeriesItemTooltip(e, el, dispatchAction);
  64329. }
  64330. // Tooltip provided directly. Like legend.
  64331. else if (el && el.tooltip) {
  64332. this._lastDataByCoordSys = null;
  64333. this._showComponentItemTooltip(e, el, dispatchAction);
  64334. }
  64335. else {
  64336. this._lastDataByCoordSys = null;
  64337. this._hide(dispatchAction);
  64338. }
  64339. },
  64340. _showOrMove: function (tooltipModel, cb) {
  64341. // showDelay is used in this case: tooltip.enterable is set
  64342. // as true. User intent to move mouse into tooltip and click
  64343. // something. `showDelay` makes it easyer to enter the content
  64344. // but tooltip do not move immediately.
  64345. var delay = tooltipModel.get('showDelay');
  64346. cb = bind(cb, this);
  64347. clearTimeout(this._showTimout);
  64348. delay > 0
  64349. ? (this._showTimout = setTimeout(cb, delay))
  64350. : cb();
  64351. },
  64352. _showAxisTooltip: function (dataByCoordSys, e) {
  64353. var ecModel = this._ecModel;
  64354. var globalTooltipModel = this._tooltipModel;
  64355. var point = [e.offsetX, e.offsetY];
  64356. var singleDefaultHTML = [];
  64357. var singleParamsList = [];
  64358. var singleTooltipModel = buildTooltipModel([
  64359. e.tooltipOption,
  64360. globalTooltipModel
  64361. ]);
  64362. var renderMode = this._renderMode;
  64363. var newLine = this._newLine;
  64364. var markers = {};
  64365. each$17(dataByCoordSys, function (itemCoordSys) {
  64366. // var coordParamList = [];
  64367. // var coordDefaultHTML = [];
  64368. // var coordTooltipModel = buildTooltipModel([
  64369. // e.tooltipOption,
  64370. // itemCoordSys.tooltipOption,
  64371. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  64372. // globalTooltipModel
  64373. // ]);
  64374. // var displayMode = coordTooltipModel.get('displayMode');
  64375. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  64376. each$17(itemCoordSys.dataByAxis, function (item) {
  64377. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  64378. var axisValue = item.value;
  64379. var seriesDefaultHTML = [];
  64380. if (!axisModel || axisValue == null) {
  64381. return;
  64382. }
  64383. var valueLabel = getValueLabel(
  64384. axisValue, axisModel.axis, ecModel,
  64385. item.seriesDataIndices,
  64386. item.valueLabelOpt
  64387. );
  64388. each$1(item.seriesDataIndices, function (idxItem) {
  64389. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  64390. var dataIndex = idxItem.dataIndexInside;
  64391. var dataParams = series && series.getDataParams(dataIndex);
  64392. dataParams.axisDim = item.axisDim;
  64393. dataParams.axisIndex = item.axisIndex;
  64394. dataParams.axisType = item.axisType;
  64395. dataParams.axisId = item.axisId;
  64396. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  64397. dataParams.axisValueLabel = valueLabel;
  64398. if (dataParams) {
  64399. singleParamsList.push(dataParams);
  64400. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  64401. var html;
  64402. if (isObject$1(seriesTooltip)) {
  64403. html = seriesTooltip.html;
  64404. var newMarkers = seriesTooltip.markers;
  64405. merge(markers, newMarkers);
  64406. }
  64407. else {
  64408. html = seriesTooltip;
  64409. }
  64410. seriesDefaultHTML.push(html);
  64411. }
  64412. });
  64413. // Default tooltip content
  64414. // FIXME
  64415. // (1) shold be the first data which has name?
  64416. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  64417. var firstLine = valueLabel;
  64418. if (renderMode !== 'html') {
  64419. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  64420. }
  64421. else {
  64422. singleDefaultHTML.push(
  64423. (firstLine ? encodeHTML(firstLine) + newLine : '')
  64424. + seriesDefaultHTML.join(newLine)
  64425. );
  64426. }
  64427. });
  64428. }, this);
  64429. // In most case, the second axis is shown upper than the first one.
  64430. singleDefaultHTML.reverse();
  64431. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  64432. var positionExpr = e.position;
  64433. this._showOrMove(singleTooltipModel, function () {
  64434. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  64435. this._updatePosition(
  64436. singleTooltipModel,
  64437. positionExpr,
  64438. point[0], point[1],
  64439. this._tooltipContent,
  64440. singleParamsList
  64441. );
  64442. }
  64443. else {
  64444. this._showTooltipContent(
  64445. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  64446. point[0], point[1], positionExpr, undefined, markers
  64447. );
  64448. }
  64449. });
  64450. // Do not trigger events here, because this branch only be entered
  64451. // from dispatchAction.
  64452. },
  64453. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  64454. var ecModel = this._ecModel;
  64455. // Use dataModel in element if possible
  64456. // Used when mouseover on a element like markPoint or edge
  64457. // In which case, the data is not main data in series.
  64458. var seriesIndex = el.seriesIndex;
  64459. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  64460. // For example, graph link.
  64461. var dataModel = el.dataModel || seriesModel;
  64462. var dataIndex = el.dataIndex;
  64463. var dataType = el.dataType;
  64464. var data = dataModel.getData();
  64465. var tooltipModel = buildTooltipModel([
  64466. data.getItemModel(dataIndex),
  64467. dataModel,
  64468. seriesModel && (seriesModel.coordinateSystem || {}).model,
  64469. this._tooltipModel
  64470. ]);
  64471. var tooltipTrigger = tooltipModel.get('trigger');
  64472. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  64473. return;
  64474. }
  64475. var params = dataModel.getDataParams(dataIndex, dataType);
  64476. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  64477. var defaultHtml;
  64478. var markers;
  64479. if (isObject$1(seriesTooltip)) {
  64480. defaultHtml = seriesTooltip.html;
  64481. markers = seriesTooltip.markers;
  64482. }
  64483. else {
  64484. defaultHtml = seriesTooltip;
  64485. markers = null;
  64486. }
  64487. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  64488. this._showOrMove(tooltipModel, function () {
  64489. this._showTooltipContent(
  64490. tooltipModel, defaultHtml, params, asyncTicket,
  64491. e.offsetX, e.offsetY, e.position, e.target, markers
  64492. );
  64493. });
  64494. // FIXME
  64495. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  64496. dispatchAction({
  64497. type: 'showTip',
  64498. dataIndexInside: dataIndex,
  64499. dataIndex: data.getRawIndex(dataIndex),
  64500. seriesIndex: seriesIndex,
  64501. from: this.uid
  64502. });
  64503. },
  64504. _showComponentItemTooltip: function (e, el, dispatchAction) {
  64505. var tooltipOpt = el.tooltip;
  64506. if (typeof tooltipOpt === 'string') {
  64507. var content = tooltipOpt;
  64508. tooltipOpt = {
  64509. content: content,
  64510. // Fixed formatter
  64511. formatter: content
  64512. };
  64513. }
  64514. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  64515. var defaultHtml = subTooltipModel.get('content');
  64516. var asyncTicket = Math.random();
  64517. // Do not check whether `trigger` is 'none' here, because `trigger`
  64518. // only works on cooridinate system. In fact, we have not found case
  64519. // that requires setting `trigger` nothing on component yet.
  64520. this._showOrMove(subTooltipModel, function () {
  64521. this._showTooltipContent(
  64522. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  64523. asyncTicket, e.offsetX, e.offsetY, e.position, el
  64524. );
  64525. });
  64526. // If not dispatch showTip, tip may be hide triggered by axis.
  64527. dispatchAction({
  64528. type: 'showTip',
  64529. from: this.uid
  64530. });
  64531. },
  64532. _showTooltipContent: function (
  64533. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers
  64534. ) {
  64535. // Reset ticket
  64536. this._ticket = '';
  64537. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  64538. return;
  64539. }
  64540. var tooltipContent = this._tooltipContent;
  64541. var formatter = tooltipModel.get('formatter');
  64542. positionExpr = positionExpr || tooltipModel.get('position');
  64543. var html = defaultHtml;
  64544. if (formatter && typeof formatter === 'string') {
  64545. html = formatTpl(formatter, params, true);
  64546. }
  64547. else if (typeof formatter === 'function') {
  64548. var callback = bind$3(function (cbTicket, html) {
  64549. if (cbTicket === this._ticket) {
  64550. tooltipContent.setContent(html, markers, tooltipModel);
  64551. this._updatePosition(
  64552. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  64553. );
  64554. }
  64555. }, this);
  64556. this._ticket = asyncTicket;
  64557. html = formatter(params, asyncTicket, callback);
  64558. }
  64559. tooltipContent.setContent(html, markers, tooltipModel);
  64560. tooltipContent.show(tooltipModel);
  64561. this._updatePosition(
  64562. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  64563. );
  64564. },
  64565. /**
  64566. * @param {string|Function|Array.<number>|Object} positionExpr
  64567. * @param {number} x Mouse x
  64568. * @param {number} y Mouse y
  64569. * @param {boolean} confine Whether confine tooltip content in view rect.
  64570. * @param {Object|<Array.<Object>} params
  64571. * @param {module:zrender/Element} el target element
  64572. * @param {module:echarts/ExtensionAPI} api
  64573. * @return {Array.<number>}
  64574. */
  64575. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  64576. var viewWidth = this._api.getWidth();
  64577. var viewHeight = this._api.getHeight();
  64578. positionExpr = positionExpr || tooltipModel.get('position');
  64579. var contentSize = content.getSize();
  64580. var align = tooltipModel.get('align');
  64581. var vAlign = tooltipModel.get('verticalAlign');
  64582. var rect = el && el.getBoundingRect().clone();
  64583. el && rect.applyTransform(el.transform);
  64584. if (typeof positionExpr === 'function') {
  64585. // Callback of position can be an array or a string specify the position
  64586. positionExpr = positionExpr([x, y], params, content.el, rect, {
  64587. viewSize: [viewWidth, viewHeight],
  64588. contentSize: contentSize.slice()
  64589. });
  64590. }
  64591. if (isArray(positionExpr)) {
  64592. x = parsePercent$2(positionExpr[0], viewWidth);
  64593. y = parsePercent$2(positionExpr[1], viewHeight);
  64594. }
  64595. else if (isObject$1(positionExpr)) {
  64596. positionExpr.width = contentSize[0];
  64597. positionExpr.height = contentSize[1];
  64598. var layoutRect = getLayoutRect(
  64599. positionExpr, {width: viewWidth, height: viewHeight}
  64600. );
  64601. x = layoutRect.x;
  64602. y = layoutRect.y;
  64603. align = null;
  64604. // When positionExpr is left/top/right/bottom,
  64605. // align and verticalAlign will not work.
  64606. vAlign = null;
  64607. }
  64608. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  64609. else if (typeof positionExpr === 'string' && el) {
  64610. var pos = calcTooltipPosition(
  64611. positionExpr, rect, contentSize
  64612. );
  64613. x = pos[0];
  64614. y = pos[1];
  64615. }
  64616. else {
  64617. var pos = refixTooltipPosition(
  64618. x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  64619. );
  64620. x = pos[0];
  64621. y = pos[1];
  64622. }
  64623. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  64624. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  64625. if (tooltipModel.get('confine')) {
  64626. var pos = confineTooltipPosition(
  64627. x, y, content, viewWidth, viewHeight
  64628. );
  64629. x = pos[0];
  64630. y = pos[1];
  64631. }
  64632. content.moveTo(x, y);
  64633. },
  64634. // FIXME
  64635. // Should we remove this but leave this to user?
  64636. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  64637. var lastCoordSys = this._lastDataByCoordSys;
  64638. var contentNotChanged = !!lastCoordSys
  64639. && lastCoordSys.length === dataByCoordSys.length;
  64640. contentNotChanged && each$17(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  64641. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  64642. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  64643. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  64644. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  64645. contentNotChanged && each$17(lastDataByAxis, function (lastItem, indexAxis) {
  64646. var thisItem = thisDataByAxis[indexAxis] || {};
  64647. var lastIndices = lastItem.seriesDataIndices || [];
  64648. var newIndices = thisItem.seriesDataIndices || [];
  64649. contentNotChanged
  64650. &= lastItem.value === thisItem.value
  64651. && lastItem.axisType === thisItem.axisType
  64652. && lastItem.axisId === thisItem.axisId
  64653. && lastIndices.length === newIndices.length;
  64654. contentNotChanged && each$17(lastIndices, function (lastIdxItem, j) {
  64655. var newIdxItem = newIndices[j];
  64656. contentNotChanged
  64657. &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  64658. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  64659. });
  64660. });
  64661. });
  64662. this._lastDataByCoordSys = dataByCoordSys;
  64663. return !!contentNotChanged;
  64664. },
  64665. _hide: function (dispatchAction) {
  64666. // Do not directly hideLater here, because this behavior may be prevented
  64667. // in dispatchAction when showTip is dispatched.
  64668. // FIXME
  64669. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  64670. this._lastDataByCoordSys = null;
  64671. dispatchAction({
  64672. type: 'hideTip',
  64673. from: this.uid
  64674. });
  64675. },
  64676. dispose: function (ecModel, api) {
  64677. if (env$1.node) {
  64678. return;
  64679. }
  64680. this._tooltipContent.hide();
  64681. unregister('itemTooltip', api);
  64682. }
  64683. });
  64684. /**
  64685. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  64686. * From top to bottom. (the last one should be globalTooltipModel);
  64687. */
  64688. function buildTooltipModel(modelCascade) {
  64689. var resultModel = modelCascade.pop();
  64690. while (modelCascade.length) {
  64691. var tooltipOpt = modelCascade.pop();
  64692. if (tooltipOpt) {
  64693. if (Model.isInstance(tooltipOpt)) {
  64694. tooltipOpt = tooltipOpt.get('tooltip', true);
  64695. }
  64696. // In each data item tooltip can be simply write:
  64697. // {
  64698. // value: 10,
  64699. // tooltip: 'Something you need to know'
  64700. // }
  64701. if (typeof tooltipOpt === 'string') {
  64702. tooltipOpt = {formatter: tooltipOpt};
  64703. }
  64704. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  64705. }
  64706. }
  64707. return resultModel;
  64708. }
  64709. function makeDispatchAction$1(payload, api) {
  64710. return payload.dispatchAction || bind(api.dispatchAction, api);
  64711. }
  64712. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  64713. var size = content.getOuterSize();
  64714. var width = size.width;
  64715. var height = size.height;
  64716. if (gapH != null) {
  64717. if (x + width + gapH > viewWidth) {
  64718. x -= width + gapH;
  64719. }
  64720. else {
  64721. x += gapH;
  64722. }
  64723. }
  64724. if (gapV != null) {
  64725. if (y + height + gapV > viewHeight) {
  64726. y -= height + gapV;
  64727. }
  64728. else {
  64729. y += gapV;
  64730. }
  64731. }
  64732. return [x, y];
  64733. }
  64734. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  64735. var size = content.getOuterSize();
  64736. var width = size.width;
  64737. var height = size.height;
  64738. x = Math.min(x + width, viewWidth) - width;
  64739. y = Math.min(y + height, viewHeight) - height;
  64740. x = Math.max(x, 0);
  64741. y = Math.max(y, 0);
  64742. return [x, y];
  64743. }
  64744. function calcTooltipPosition(position, rect, contentSize) {
  64745. var domWidth = contentSize[0];
  64746. var domHeight = contentSize[1];
  64747. var gap = 5;
  64748. var x = 0;
  64749. var y = 0;
  64750. var rectWidth = rect.width;
  64751. var rectHeight = rect.height;
  64752. switch (position) {
  64753. case 'inside':
  64754. x = rect.x + rectWidth / 2 - domWidth / 2;
  64755. y = rect.y + rectHeight / 2 - domHeight / 2;
  64756. break;
  64757. case 'top':
  64758. x = rect.x + rectWidth / 2 - domWidth / 2;
  64759. y = rect.y - domHeight - gap;
  64760. break;
  64761. case 'bottom':
  64762. x = rect.x + rectWidth / 2 - domWidth / 2;
  64763. y = rect.y + rectHeight + gap;
  64764. break;
  64765. case 'left':
  64766. x = rect.x - domWidth - gap;
  64767. y = rect.y + rectHeight / 2 - domHeight / 2;
  64768. break;
  64769. case 'right':
  64770. x = rect.x + rectWidth + gap;
  64771. y = rect.y + rectHeight / 2 - domHeight / 2;
  64772. }
  64773. return [x, y];
  64774. }
  64775. function isCenterAlign(align) {
  64776. return align === 'center' || align === 'middle';
  64777. }
  64778. /*
  64779. * Licensed to the Apache Software Foundation (ASF) under one
  64780. * or more contributor license agreements. See the NOTICE file
  64781. * distributed with this work for additional information
  64782. * regarding copyright ownership. The ASF licenses this file
  64783. * to you under the Apache License, Version 2.0 (the
  64784. * "License"); you may not use this file except in compliance
  64785. * with the License. You may obtain a copy of the License at
  64786. *
  64787. * http://www.apache.org/licenses/LICENSE-2.0
  64788. *
  64789. * Unless required by applicable law or agreed to in writing,
  64790. * software distributed under the License is distributed on an
  64791. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64792. * KIND, either express or implied. See the License for the
  64793. * specific language governing permissions and limitations
  64794. * under the License.
  64795. */
  64796. // FIXME Better way to pack data in graphic element
  64797. /**
  64798. * @action
  64799. * @property {string} type
  64800. * @property {number} seriesIndex
  64801. * @property {number} dataIndex
  64802. * @property {number} [x]
  64803. * @property {number} [y]
  64804. */
  64805. registerAction(
  64806. {
  64807. type: 'showTip',
  64808. event: 'showTip',
  64809. update: 'tooltip:manuallyShowTip'
  64810. },
  64811. // noop
  64812. function () {}
  64813. );
  64814. registerAction(
  64815. {
  64816. type: 'hideTip',
  64817. event: 'hideTip',
  64818. update: 'tooltip:manuallyHideTip'
  64819. },
  64820. // noop
  64821. function () {}
  64822. );
  64823. /*
  64824. * Licensed to the Apache Software Foundation (ASF) under one
  64825. * or more contributor license agreements. See the NOTICE file
  64826. * distributed with this work for additional information
  64827. * regarding copyright ownership. The ASF licenses this file
  64828. * to you under the Apache License, Version 2.0 (the
  64829. * "License"); you may not use this file except in compliance
  64830. * with the License. You may obtain a copy of the License at
  64831. *
  64832. * http://www.apache.org/licenses/LICENSE-2.0
  64833. *
  64834. * Unless required by applicable law or agreed to in writing,
  64835. * software distributed under the License is distributed on an
  64836. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64837. * KIND, either express or implied. See the License for the
  64838. * specific language governing permissions and limitations
  64839. * under the License.
  64840. */
  64841. function getSeriesStackId$1(seriesModel) {
  64842. return seriesModel.get('stack')
  64843. || '__ec_stack_' + seriesModel.seriesIndex;
  64844. }
  64845. function getAxisKey$1(axis) {
  64846. return axis.dim;
  64847. }
  64848. /**
  64849. * @param {string} seriesType
  64850. * @param {module:echarts/model/Global} ecModel
  64851. * @param {module:echarts/ExtensionAPI} api
  64852. */
  64853. function barLayoutPolar(seriesType, ecModel, api) {
  64854. // FIXME
  64855. // Revert becuase it brings bar progressive bug.
  64856. // The complete fix will be added in the next version.
  64857. var width = api.getWidth();
  64858. var height = api.getHeight();
  64859. var lastStackCoords = {};
  64860. var barWidthAndOffset = calRadialBar(
  64861. filter(
  64862. ecModel.getSeriesByType(seriesType),
  64863. function (seriesModel) {
  64864. return !ecModel.isSeriesFiltered(seriesModel)
  64865. && seriesModel.coordinateSystem
  64866. && seriesModel.coordinateSystem.type === 'polar';
  64867. }
  64868. )
  64869. );
  64870. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  64871. // Check series coordinate, do layout for polar only
  64872. if (seriesModel.coordinateSystem.type !== 'polar') {
  64873. return;
  64874. }
  64875. var data = seriesModel.getData();
  64876. var polar = seriesModel.coordinateSystem;
  64877. var baseAxis = polar.getBaseAxis();
  64878. var stackId = getSeriesStackId$1(seriesModel);
  64879. var columnLayoutInfo
  64880. = barWidthAndOffset[getAxisKey$1(baseAxis)][stackId];
  64881. var columnOffset = columnLayoutInfo.offset;
  64882. var columnWidth = columnLayoutInfo.width;
  64883. var valueAxis = polar.getOtherAxis(baseAxis);
  64884. var cx = seriesModel.coordinateSystem.cx;
  64885. var cy = seriesModel.coordinateSystem.cy;
  64886. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  64887. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  64888. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  64889. var valueDim = data.mapDimension(valueAxis.dim);
  64890. var baseDim = data.mapDimension(baseAxis.dim);
  64891. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  64892. var valueAxisStart = valueAxis.getExtent()[0];
  64893. for (var idx = 0, len = data.count(); idx < len; idx++) {
  64894. var value = data.get(valueDim, idx);
  64895. var baseValue = data.get(baseDim, idx);
  64896. if (isNaN(value)) {
  64897. continue;
  64898. }
  64899. var sign = value >= 0 ? 'p' : 'n';
  64900. var baseCoord = valueAxisStart;
  64901. // Because of the barMinHeight, we can not use the value in
  64902. // stackResultDimension directly.
  64903. // Only ordinal axis can be stacked.
  64904. if (stacked) {
  64905. if (!lastStackCoords[stackId][baseValue]) {
  64906. lastStackCoords[stackId][baseValue] = {
  64907. p: valueAxisStart, // Positive stack
  64908. n: valueAxisStart // Negative stack
  64909. };
  64910. }
  64911. // Should also consider #4243
  64912. baseCoord = lastStackCoords[stackId][baseValue][sign];
  64913. }
  64914. var r0;
  64915. var r;
  64916. var startAngle;
  64917. var endAngle;
  64918. // radial sector
  64919. if (valueAxis.dim === 'radius') {
  64920. var radiusSpan = valueAxis.dataToRadius(value) - valueAxisStart;
  64921. var angle = baseAxis.dataToAngle(baseValue);
  64922. if (Math.abs(radiusSpan) < barMinHeight) {
  64923. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  64924. }
  64925. r0 = baseCoord;
  64926. r = baseCoord + radiusSpan;
  64927. startAngle = angle - columnOffset;
  64928. endAngle = startAngle - columnWidth;
  64929. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  64930. }
  64931. // tangential sector
  64932. else {
  64933. // angleAxis must be clamped.
  64934. var angleSpan = valueAxis.dataToAngle(value, true) - valueAxisStart;
  64935. var radius = baseAxis.dataToRadius(baseValue);
  64936. if (Math.abs(angleSpan) < barMinAngle) {
  64937. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  64938. }
  64939. r0 = radius + columnOffset;
  64940. r = r0 + columnWidth;
  64941. startAngle = baseCoord;
  64942. endAngle = baseCoord + angleSpan;
  64943. // if the previous stack is at the end of the ring,
  64944. // add a round to differentiate it from origin
  64945. // var extent = angleAxis.getExtent();
  64946. // var stackCoord = angle;
  64947. // if (stackCoord === extent[0] && value > 0) {
  64948. // stackCoord = extent[1];
  64949. // }
  64950. // else if (stackCoord === extent[1] && value < 0) {
  64951. // stackCoord = extent[0];
  64952. // }
  64953. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  64954. }
  64955. data.setItemLayout(idx, {
  64956. cx: cx,
  64957. cy: cy,
  64958. r0: r0,
  64959. r: r,
  64960. // Consider that positive angle is anti-clockwise,
  64961. // while positive radian of sector is clockwise
  64962. startAngle: -startAngle * Math.PI / 180,
  64963. endAngle: -endAngle * Math.PI / 180
  64964. });
  64965. }
  64966. }, this);
  64967. }
  64968. /**
  64969. * Calculate bar width and offset for radial bar charts
  64970. */
  64971. function calRadialBar(barSeries, api) {
  64972. // Columns info on each category axis. Key is polar name
  64973. var columnsMap = {};
  64974. each$1(barSeries, function (seriesModel, idx) {
  64975. var data = seriesModel.getData();
  64976. var polar = seriesModel.coordinateSystem;
  64977. var baseAxis = polar.getBaseAxis();
  64978. var axisExtent = baseAxis.getExtent();
  64979. var bandWidth = baseAxis.type === 'category'
  64980. ? baseAxis.getBandWidth()
  64981. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  64982. var columnsOnAxis = columnsMap[getAxisKey$1(baseAxis)] || {
  64983. bandWidth: bandWidth,
  64984. remainedWidth: bandWidth,
  64985. autoWidthCount: 0,
  64986. categoryGap: '20%',
  64987. gap: '30%',
  64988. stacks: {}
  64989. };
  64990. var stacks = columnsOnAxis.stacks;
  64991. columnsMap[getAxisKey$1(baseAxis)] = columnsOnAxis;
  64992. var stackId = getSeriesStackId$1(seriesModel);
  64993. if (!stacks[stackId]) {
  64994. columnsOnAxis.autoWidthCount++;
  64995. }
  64996. stacks[stackId] = stacks[stackId] || {
  64997. width: 0,
  64998. maxWidth: 0
  64999. };
  65000. var barWidth = parsePercent$1(
  65001. seriesModel.get('barWidth'),
  65002. bandWidth
  65003. );
  65004. var barMaxWidth = parsePercent$1(
  65005. seriesModel.get('barMaxWidth'),
  65006. bandWidth
  65007. );
  65008. var barGap = seriesModel.get('barGap');
  65009. var barCategoryGap = seriesModel.get('barCategoryGap');
  65010. if (barWidth && !stacks[stackId].width) {
  65011. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  65012. stacks[stackId].width = barWidth;
  65013. columnsOnAxis.remainedWidth -= barWidth;
  65014. }
  65015. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  65016. (barGap != null) && (columnsOnAxis.gap = barGap);
  65017. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  65018. });
  65019. var result = {};
  65020. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  65021. result[coordSysName] = {};
  65022. var stacks = columnsOnAxis.stacks;
  65023. var bandWidth = columnsOnAxis.bandWidth;
  65024. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  65025. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  65026. var remainedWidth = columnsOnAxis.remainedWidth;
  65027. var autoWidthCount = columnsOnAxis.autoWidthCount;
  65028. var autoWidth = (remainedWidth - categoryGap)
  65029. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  65030. autoWidth = Math.max(autoWidth, 0);
  65031. // Find if any auto calculated bar exceeded maxBarWidth
  65032. each$1(stacks, function (column, stack) {
  65033. var maxWidth = column.maxWidth;
  65034. if (maxWidth && maxWidth < autoWidth) {
  65035. maxWidth = Math.min(maxWidth, remainedWidth);
  65036. if (column.width) {
  65037. maxWidth = Math.min(maxWidth, column.width);
  65038. }
  65039. remainedWidth -= maxWidth;
  65040. column.width = maxWidth;
  65041. autoWidthCount--;
  65042. }
  65043. });
  65044. // Recalculate width again
  65045. autoWidth = (remainedWidth - categoryGap)
  65046. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  65047. autoWidth = Math.max(autoWidth, 0);
  65048. var widthSum = 0;
  65049. var lastColumn;
  65050. each$1(stacks, function (column, idx) {
  65051. if (!column.width) {
  65052. column.width = autoWidth;
  65053. }
  65054. lastColumn = column;
  65055. widthSum += column.width * (1 + barGapPercent);
  65056. });
  65057. if (lastColumn) {
  65058. widthSum -= lastColumn.width * barGapPercent;
  65059. }
  65060. var offset = -widthSum / 2;
  65061. each$1(stacks, function (column, stackId) {
  65062. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  65063. offset: offset,
  65064. width: column.width
  65065. };
  65066. offset += column.width * (1 + barGapPercent);
  65067. });
  65068. });
  65069. return result;
  65070. }
  65071. /*
  65072. * Licensed to the Apache Software Foundation (ASF) under one
  65073. * or more contributor license agreements. See the NOTICE file
  65074. * distributed with this work for additional information
  65075. * regarding copyright ownership. The ASF licenses this file
  65076. * to you under the Apache License, Version 2.0 (the
  65077. * "License"); you may not use this file except in compliance
  65078. * with the License. You may obtain a copy of the License at
  65079. *
  65080. * http://www.apache.org/licenses/LICENSE-2.0
  65081. *
  65082. * Unless required by applicable law or agreed to in writing,
  65083. * software distributed under the License is distributed on an
  65084. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65085. * KIND, either express or implied. See the License for the
  65086. * specific language governing permissions and limitations
  65087. * under the License.
  65088. */
  65089. function RadiusAxis(scale, radiusExtent) {
  65090. Axis.call(this, 'radius', scale, radiusExtent);
  65091. /**
  65092. * Axis type
  65093. * - 'category'
  65094. * - 'value'
  65095. * - 'time'
  65096. * - 'log'
  65097. * @type {string}
  65098. */
  65099. this.type = 'category';
  65100. }
  65101. RadiusAxis.prototype = {
  65102. constructor: RadiusAxis,
  65103. /**
  65104. * @override
  65105. */
  65106. pointToData: function (point, clamp) {
  65107. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  65108. },
  65109. dataToRadius: Axis.prototype.dataToCoord,
  65110. radiusToData: Axis.prototype.coordToData
  65111. };
  65112. inherits(RadiusAxis, Axis);
  65113. /*
  65114. * Licensed to the Apache Software Foundation (ASF) under one
  65115. * or more contributor license agreements. See the NOTICE file
  65116. * distributed with this work for additional information
  65117. * regarding copyright ownership. The ASF licenses this file
  65118. * to you under the Apache License, Version 2.0 (the
  65119. * "License"); you may not use this file except in compliance
  65120. * with the License. You may obtain a copy of the License at
  65121. *
  65122. * http://www.apache.org/licenses/LICENSE-2.0
  65123. *
  65124. * Unless required by applicable law or agreed to in writing,
  65125. * software distributed under the License is distributed on an
  65126. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65127. * KIND, either express or implied. See the License for the
  65128. * specific language governing permissions and limitations
  65129. * under the License.
  65130. */
  65131. var inner$12 = makeInner();
  65132. function AngleAxis(scale, angleExtent) {
  65133. angleExtent = angleExtent || [0, 360];
  65134. Axis.call(this, 'angle', scale, angleExtent);
  65135. /**
  65136. * Axis type
  65137. * - 'category'
  65138. * - 'value'
  65139. * - 'time'
  65140. * - 'log'
  65141. * @type {string}
  65142. */
  65143. this.type = 'category';
  65144. }
  65145. AngleAxis.prototype = {
  65146. constructor: AngleAxis,
  65147. /**
  65148. * @override
  65149. */
  65150. pointToData: function (point, clamp) {
  65151. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  65152. },
  65153. dataToAngle: Axis.prototype.dataToCoord,
  65154. angleToData: Axis.prototype.coordToData,
  65155. /**
  65156. * Only be called in category axis.
  65157. * Angle axis uses text height to decide interval
  65158. *
  65159. * @override
  65160. * @return {number} Auto interval for cateogry axis tick and label
  65161. */
  65162. calculateCategoryInterval: function () {
  65163. var axis = this;
  65164. var labelModel = axis.getLabelModel();
  65165. var ordinalScale = axis.scale;
  65166. var ordinalExtent = ordinalScale.getExtent();
  65167. // Providing this method is for optimization:
  65168. // avoid generating a long array by `getTicks`
  65169. // in large category data case.
  65170. var tickCount = ordinalScale.count();
  65171. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  65172. return 0;
  65173. }
  65174. var tickValue = ordinalExtent[0];
  65175. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  65176. var unitH = Math.abs(unitSpan);
  65177. // Not precise, just use height as text width
  65178. // and each distance from axis line yet.
  65179. var rect = getBoundingRect(
  65180. tickValue, labelModel.getFont(), 'center', 'top'
  65181. );
  65182. var maxH = Math.max(rect.height, 7);
  65183. var dh = maxH / unitH;
  65184. // 0/0 is NaN, 1/0 is Infinity.
  65185. isNaN(dh) && (dh = Infinity);
  65186. var interval = Math.max(0, Math.floor(dh));
  65187. var cache = inner$12(axis.model);
  65188. var lastAutoInterval = cache.lastAutoInterval;
  65189. var lastTickCount = cache.lastTickCount;
  65190. // Use cache to keep interval stable while moving zoom window,
  65191. // otherwise the calculated interval might jitter when the zoom
  65192. // window size is close to the interval-changing size.
  65193. if (lastAutoInterval != null
  65194. && lastTickCount != null
  65195. && Math.abs(lastAutoInterval - interval) <= 1
  65196. && Math.abs(lastTickCount - tickCount) <= 1
  65197. // Always choose the bigger one, otherwise the critical
  65198. // point is not the same when zooming in or zooming out.
  65199. && lastAutoInterval > interval
  65200. ) {
  65201. interval = lastAutoInterval;
  65202. }
  65203. // Only update cache if cache not used, otherwise the
  65204. // changing of interval is too insensitive.
  65205. else {
  65206. cache.lastTickCount = tickCount;
  65207. cache.lastAutoInterval = interval;
  65208. }
  65209. return interval;
  65210. }
  65211. };
  65212. inherits(AngleAxis, Axis);
  65213. /*
  65214. * Licensed to the Apache Software Foundation (ASF) under one
  65215. * or more contributor license agreements. See the NOTICE file
  65216. * distributed with this work for additional information
  65217. * regarding copyright ownership. The ASF licenses this file
  65218. * to you under the Apache License, Version 2.0 (the
  65219. * "License"); you may not use this file except in compliance
  65220. * with the License. You may obtain a copy of the License at
  65221. *
  65222. * http://www.apache.org/licenses/LICENSE-2.0
  65223. *
  65224. * Unless required by applicable law or agreed to in writing,
  65225. * software distributed under the License is distributed on an
  65226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65227. * KIND, either express or implied. See the License for the
  65228. * specific language governing permissions and limitations
  65229. * under the License.
  65230. */
  65231. /**
  65232. * @module echarts/coord/polar/Polar
  65233. */
  65234. /**
  65235. * @alias {module:echarts/coord/polar/Polar}
  65236. * @constructor
  65237. * @param {string} name
  65238. */
  65239. var Polar = function (name) {
  65240. /**
  65241. * @type {string}
  65242. */
  65243. this.name = name || '';
  65244. /**
  65245. * x of polar center
  65246. * @type {number}
  65247. */
  65248. this.cx = 0;
  65249. /**
  65250. * y of polar center
  65251. * @type {number}
  65252. */
  65253. this.cy = 0;
  65254. /**
  65255. * @type {module:echarts/coord/polar/RadiusAxis}
  65256. * @private
  65257. */
  65258. this._radiusAxis = new RadiusAxis();
  65259. /**
  65260. * @type {module:echarts/coord/polar/AngleAxis}
  65261. * @private
  65262. */
  65263. this._angleAxis = new AngleAxis();
  65264. this._radiusAxis.polar = this._angleAxis.polar = this;
  65265. };
  65266. Polar.prototype = {
  65267. type: 'polar',
  65268. axisPointerEnabled: true,
  65269. constructor: Polar,
  65270. /**
  65271. * @param {Array.<string>}
  65272. * @readOnly
  65273. */
  65274. dimensions: ['radius', 'angle'],
  65275. /**
  65276. * @type {module:echarts/coord/PolarModel}
  65277. */
  65278. model: null,
  65279. /**
  65280. * If contain coord
  65281. * @param {Array.<number>} point
  65282. * @return {boolean}
  65283. */
  65284. containPoint: function (point) {
  65285. var coord = this.pointToCoord(point);
  65286. return this._radiusAxis.contain(coord[0])
  65287. && this._angleAxis.contain(coord[1]);
  65288. },
  65289. /**
  65290. * If contain data
  65291. * @param {Array.<number>} data
  65292. * @return {boolean}
  65293. */
  65294. containData: function (data) {
  65295. return this._radiusAxis.containData(data[0])
  65296. && this._angleAxis.containData(data[1]);
  65297. },
  65298. /**
  65299. * @param {string} dim
  65300. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65301. */
  65302. getAxis: function (dim) {
  65303. return this['_' + dim + 'Axis'];
  65304. },
  65305. /**
  65306. * @return {Array.<module:echarts/coord/Axis>}
  65307. */
  65308. getAxes: function () {
  65309. return [this._radiusAxis, this._angleAxis];
  65310. },
  65311. /**
  65312. * Get axes by type of scale
  65313. * @param {string} scaleType
  65314. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65315. */
  65316. getAxesByScale: function (scaleType) {
  65317. var axes = [];
  65318. var angleAxis = this._angleAxis;
  65319. var radiusAxis = this._radiusAxis;
  65320. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  65321. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  65322. return axes;
  65323. },
  65324. /**
  65325. * @return {module:echarts/coord/polar/AngleAxis}
  65326. */
  65327. getAngleAxis: function () {
  65328. return this._angleAxis;
  65329. },
  65330. /**
  65331. * @return {module:echarts/coord/polar/RadiusAxis}
  65332. */
  65333. getRadiusAxis: function () {
  65334. return this._radiusAxis;
  65335. },
  65336. /**
  65337. * @param {module:echarts/coord/polar/Axis}
  65338. * @return {module:echarts/coord/polar/Axis}
  65339. */
  65340. getOtherAxis: function (axis) {
  65341. var angleAxis = this._angleAxis;
  65342. return axis === angleAxis ? this._radiusAxis : angleAxis;
  65343. },
  65344. /**
  65345. * Base axis will be used on stacking.
  65346. *
  65347. * @return {module:echarts/coord/polar/Axis}
  65348. */
  65349. getBaseAxis: function () {
  65350. return this.getAxesByScale('ordinal')[0]
  65351. || this.getAxesByScale('time')[0]
  65352. || this.getAngleAxis();
  65353. },
  65354. /**
  65355. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  65356. * @return {Object} {baseAxes: [], otherAxes: []}
  65357. */
  65358. getTooltipAxes: function (dim) {
  65359. var baseAxis = (dim != null && dim !== 'auto')
  65360. ? this.getAxis(dim) : this.getBaseAxis();
  65361. return {
  65362. baseAxes: [baseAxis],
  65363. otherAxes: [this.getOtherAxis(baseAxis)]
  65364. };
  65365. },
  65366. /**
  65367. * Convert a single data item to (x, y) point.
  65368. * Parameter data is an array which the first element is radius and the second is angle
  65369. * @param {Array.<number>} data
  65370. * @param {boolean} [clamp=false]
  65371. * @return {Array.<number>}
  65372. */
  65373. dataToPoint: function (data, clamp) {
  65374. return this.coordToPoint([
  65375. this._radiusAxis.dataToRadius(data[0], clamp),
  65376. this._angleAxis.dataToAngle(data[1], clamp)
  65377. ]);
  65378. },
  65379. /**
  65380. * Convert a (x, y) point to data
  65381. * @param {Array.<number>} point
  65382. * @param {boolean} [clamp=false]
  65383. * @return {Array.<number>}
  65384. */
  65385. pointToData: function (point, clamp) {
  65386. var coord = this.pointToCoord(point);
  65387. return [
  65388. this._radiusAxis.radiusToData(coord[0], clamp),
  65389. this._angleAxis.angleToData(coord[1], clamp)
  65390. ];
  65391. },
  65392. /**
  65393. * Convert a (x, y) point to (radius, angle) coord
  65394. * @param {Array.<number>} point
  65395. * @return {Array.<number>}
  65396. */
  65397. pointToCoord: function (point) {
  65398. var dx = point[0] - this.cx;
  65399. var dy = point[1] - this.cy;
  65400. var angleAxis = this.getAngleAxis();
  65401. var extent = angleAxis.getExtent();
  65402. var minAngle = Math.min(extent[0], extent[1]);
  65403. var maxAngle = Math.max(extent[0], extent[1]);
  65404. // Fix fixed extent in polarCreator
  65405. // FIXME
  65406. angleAxis.inverse
  65407. ? (minAngle = maxAngle - 360)
  65408. : (maxAngle = minAngle + 360);
  65409. var radius = Math.sqrt(dx * dx + dy * dy);
  65410. dx /= radius;
  65411. dy /= radius;
  65412. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  65413. // move to angleExtent
  65414. var dir = radian < minAngle ? 1 : -1;
  65415. while (radian < minAngle || radian > maxAngle) {
  65416. radian += dir * 360;
  65417. }
  65418. return [radius, radian];
  65419. },
  65420. /**
  65421. * Convert a (radius, angle) coord to (x, y) point
  65422. * @param {Array.<number>} coord
  65423. * @return {Array.<number>}
  65424. */
  65425. coordToPoint: function (coord) {
  65426. var radius = coord[0];
  65427. var radian = coord[1] / 180 * Math.PI;
  65428. var x = Math.cos(radian) * radius + this.cx;
  65429. // Inverse the y
  65430. var y = -Math.sin(radian) * radius + this.cy;
  65431. return [x, y];
  65432. }
  65433. };
  65434. /*
  65435. * Licensed to the Apache Software Foundation (ASF) under one
  65436. * or more contributor license agreements. See the NOTICE file
  65437. * distributed with this work for additional information
  65438. * regarding copyright ownership. The ASF licenses this file
  65439. * to you under the Apache License, Version 2.0 (the
  65440. * "License"); you may not use this file except in compliance
  65441. * with the License. You may obtain a copy of the License at
  65442. *
  65443. * http://www.apache.org/licenses/LICENSE-2.0
  65444. *
  65445. * Unless required by applicable law or agreed to in writing,
  65446. * software distributed under the License is distributed on an
  65447. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65448. * KIND, either express or implied. See the License for the
  65449. * specific language governing permissions and limitations
  65450. * under the License.
  65451. */
  65452. var PolarAxisModel = ComponentModel.extend({
  65453. type: 'polarAxis',
  65454. /**
  65455. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65456. */
  65457. axis: null,
  65458. /**
  65459. * @override
  65460. */
  65461. getCoordSysModel: function () {
  65462. return this.ecModel.queryComponents({
  65463. mainType: 'polar',
  65464. index: this.option.polarIndex,
  65465. id: this.option.polarId
  65466. })[0];
  65467. }
  65468. });
  65469. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  65470. var polarAxisDefaultExtendedOption = {
  65471. angle: {
  65472. // polarIndex: 0,
  65473. // polarId: '',
  65474. startAngle: 90,
  65475. clockwise: true,
  65476. splitNumber: 12,
  65477. axisLabel: {
  65478. rotate: false
  65479. }
  65480. },
  65481. radius: {
  65482. // polarIndex: 0,
  65483. // polarId: '',
  65484. splitNumber: 5
  65485. }
  65486. };
  65487. function getAxisType$3(axisDim, option) {
  65488. // Default axis with data is category axis
  65489. return option.type || (option.data ? 'category' : 'value');
  65490. }
  65491. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  65492. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  65493. /*
  65494. * Licensed to the Apache Software Foundation (ASF) under one
  65495. * or more contributor license agreements. See the NOTICE file
  65496. * distributed with this work for additional information
  65497. * regarding copyright ownership. The ASF licenses this file
  65498. * to you under the Apache License, Version 2.0 (the
  65499. * "License"); you may not use this file except in compliance
  65500. * with the License. You may obtain a copy of the License at
  65501. *
  65502. * http://www.apache.org/licenses/LICENSE-2.0
  65503. *
  65504. * Unless required by applicable law or agreed to in writing,
  65505. * software distributed under the License is distributed on an
  65506. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65507. * KIND, either express or implied. See the License for the
  65508. * specific language governing permissions and limitations
  65509. * under the License.
  65510. */
  65511. extendComponentModel({
  65512. type: 'polar',
  65513. dependencies: ['polarAxis', 'angleAxis'],
  65514. /**
  65515. * @type {module:echarts/coord/polar/Polar}
  65516. */
  65517. coordinateSystem: null,
  65518. /**
  65519. * @param {string} axisType
  65520. * @return {module:echarts/coord/polar/AxisModel}
  65521. */
  65522. findAxisModel: function (axisType) {
  65523. var foundAxisModel;
  65524. var ecModel = this.ecModel;
  65525. ecModel.eachComponent(axisType, function (axisModel) {
  65526. if (axisModel.getCoordSysModel() === this) {
  65527. foundAxisModel = axisModel;
  65528. }
  65529. }, this);
  65530. return foundAxisModel;
  65531. },
  65532. defaultOption: {
  65533. zlevel: 0,
  65534. z: 0,
  65535. center: ['50%', '50%'],
  65536. radius: '80%'
  65537. }
  65538. });
  65539. /*
  65540. * Licensed to the Apache Software Foundation (ASF) under one
  65541. * or more contributor license agreements. See the NOTICE file
  65542. * distributed with this work for additional information
  65543. * regarding copyright ownership. The ASF licenses this file
  65544. * to you under the Apache License, Version 2.0 (the
  65545. * "License"); you may not use this file except in compliance
  65546. * with the License. You may obtain a copy of the License at
  65547. *
  65548. * http://www.apache.org/licenses/LICENSE-2.0
  65549. *
  65550. * Unless required by applicable law or agreed to in writing,
  65551. * software distributed under the License is distributed on an
  65552. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65553. * KIND, either express or implied. See the License for the
  65554. * specific language governing permissions and limitations
  65555. * under the License.
  65556. */
  65557. // TODO Axis scale
  65558. /**
  65559. * Resize method bound to the polar
  65560. * @param {module:echarts/coord/polar/PolarModel} polarModel
  65561. * @param {module:echarts/ExtensionAPI} api
  65562. */
  65563. function resizePolar(polar, polarModel, api) {
  65564. var center = polarModel.get('center');
  65565. var width = api.getWidth();
  65566. var height = api.getHeight();
  65567. polar.cx = parsePercent$1(center[0], width);
  65568. polar.cy = parsePercent$1(center[1], height);
  65569. var radiusAxis = polar.getRadiusAxis();
  65570. var size = Math.min(width, height) / 2;
  65571. var radius = parsePercent$1(polarModel.get('radius'), size);
  65572. radiusAxis.inverse
  65573. ? radiusAxis.setExtent(radius, 0)
  65574. : radiusAxis.setExtent(0, radius);
  65575. }
  65576. /**
  65577. * Update polar
  65578. */
  65579. function updatePolarScale(ecModel, api) {
  65580. var polar = this;
  65581. var angleAxis = polar.getAngleAxis();
  65582. var radiusAxis = polar.getRadiusAxis();
  65583. // Reset scale
  65584. angleAxis.scale.setExtent(Infinity, -Infinity);
  65585. radiusAxis.scale.setExtent(Infinity, -Infinity);
  65586. ecModel.eachSeries(function (seriesModel) {
  65587. if (seriesModel.coordinateSystem === polar) {
  65588. var data = seriesModel.getData();
  65589. each$1(data.mapDimension('radius', true), function (dim) {
  65590. radiusAxis.scale.unionExtentFromData(
  65591. data, getStackedDimension(data, dim)
  65592. );
  65593. });
  65594. each$1(data.mapDimension('angle', true), function (dim) {
  65595. angleAxis.scale.unionExtentFromData(
  65596. data, getStackedDimension(data, dim)
  65597. );
  65598. });
  65599. }
  65600. });
  65601. niceScaleExtent(angleAxis.scale, angleAxis.model);
  65602. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  65603. // Fix extent of category angle axis
  65604. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  65605. var extent = angleAxis.getExtent();
  65606. var diff = 360 / angleAxis.scale.count();
  65607. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  65608. angleAxis.setExtent(extent[0], extent[1]);
  65609. }
  65610. }
  65611. /**
  65612. * Set common axis properties
  65613. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  65614. * @param {module:echarts/coord/polar/AxisModel}
  65615. * @inner
  65616. */
  65617. function setAxis(axis, axisModel) {
  65618. axis.type = axisModel.get('type');
  65619. axis.scale = createScaleByModel(axisModel);
  65620. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  65621. axis.inverse = axisModel.get('inverse');
  65622. if (axisModel.mainType === 'angleAxis') {
  65623. axis.inverse ^= axisModel.get('clockwise');
  65624. var startAngle = axisModel.get('startAngle');
  65625. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  65626. }
  65627. // Inject axis instance
  65628. axisModel.axis = axis;
  65629. axis.model = axisModel;
  65630. }
  65631. var polarCreator = {
  65632. dimensions: Polar.prototype.dimensions,
  65633. create: function (ecModel, api) {
  65634. var polarList = [];
  65635. ecModel.eachComponent('polar', function (polarModel, idx) {
  65636. var polar = new Polar(idx);
  65637. // Inject resize and update method
  65638. polar.update = updatePolarScale;
  65639. var radiusAxis = polar.getRadiusAxis();
  65640. var angleAxis = polar.getAngleAxis();
  65641. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  65642. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  65643. setAxis(radiusAxis, radiusAxisModel);
  65644. setAxis(angleAxis, angleAxisModel);
  65645. resizePolar(polar, polarModel, api);
  65646. polarList.push(polar);
  65647. polarModel.coordinateSystem = polar;
  65648. polar.model = polarModel;
  65649. });
  65650. // Inject coordinateSystem to series
  65651. ecModel.eachSeries(function (seriesModel) {
  65652. if (seriesModel.get('coordinateSystem') === 'polar') {
  65653. var polarModel = ecModel.queryComponents({
  65654. mainType: 'polar',
  65655. index: seriesModel.get('polarIndex'),
  65656. id: seriesModel.get('polarId')
  65657. })[0];
  65658. if (__DEV__) {
  65659. if (!polarModel) {
  65660. throw new Error(
  65661. 'Polar "' + retrieve(
  65662. seriesModel.get('polarIndex'),
  65663. seriesModel.get('polarId'),
  65664. 0
  65665. ) + '" not found'
  65666. );
  65667. }
  65668. }
  65669. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  65670. }
  65671. });
  65672. return polarList;
  65673. }
  65674. };
  65675. CoordinateSystemManager.register('polar', polarCreator);
  65676. /*
  65677. * Licensed to the Apache Software Foundation (ASF) under one
  65678. * or more contributor license agreements. See the NOTICE file
  65679. * distributed with this work for additional information
  65680. * regarding copyright ownership. The ASF licenses this file
  65681. * to you under the Apache License, Version 2.0 (the
  65682. * "License"); you may not use this file except in compliance
  65683. * with the License. You may obtain a copy of the License at
  65684. *
  65685. * http://www.apache.org/licenses/LICENSE-2.0
  65686. *
  65687. * Unless required by applicable law or agreed to in writing,
  65688. * software distributed under the License is distributed on an
  65689. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65690. * KIND, either express or implied. See the License for the
  65691. * specific language governing permissions and limitations
  65692. * under the License.
  65693. */
  65694. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'splitLine', 'splitArea'];
  65695. function getAxisLineShape(polar, rExtent, angle) {
  65696. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  65697. var start = polar.coordToPoint([rExtent[0], angle]);
  65698. var end = polar.coordToPoint([rExtent[1], angle]);
  65699. return {
  65700. x1: start[0],
  65701. y1: start[1],
  65702. x2: end[0],
  65703. y2: end[1]
  65704. };
  65705. }
  65706. function getRadiusIdx(polar) {
  65707. var radiusAxis = polar.getRadiusAxis();
  65708. return radiusAxis.inverse ? 0 : 1;
  65709. }
  65710. // Remove the last tick which will overlap the first tick
  65711. function fixAngleOverlap(list) {
  65712. var firstItem = list[0];
  65713. var lastItem = list[list.length - 1];
  65714. if (firstItem
  65715. && lastItem
  65716. && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4
  65717. ) {
  65718. list.pop();
  65719. }
  65720. }
  65721. AxisView.extend({
  65722. type: 'angleAxis',
  65723. axisPointerClass: 'PolarAxisPointer',
  65724. render: function (angleAxisModel, ecModel) {
  65725. this.group.removeAll();
  65726. if (!angleAxisModel.get('show')) {
  65727. return;
  65728. }
  65729. var angleAxis = angleAxisModel.axis;
  65730. var polar = angleAxis.polar;
  65731. var radiusExtent = polar.getRadiusAxis().getExtent();
  65732. var ticksAngles = angleAxis.getTicksCoords();
  65733. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  65734. var labelItem = clone(labelItem);
  65735. labelItem.coord = angleAxis.dataToCoord(labelItem.tickValue);
  65736. return labelItem;
  65737. });
  65738. fixAngleOverlap(labels);
  65739. fixAngleOverlap(ticksAngles);
  65740. each$1(elementList$1, function (name) {
  65741. if (angleAxisModel.get(name + '.show')
  65742. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  65743. ) {
  65744. this['_' + name](angleAxisModel, polar, ticksAngles, radiusExtent, labels);
  65745. }
  65746. }, this);
  65747. },
  65748. /**
  65749. * @private
  65750. */
  65751. _axisLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  65752. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  65753. var circle = new Circle({
  65754. shape: {
  65755. cx: polar.cx,
  65756. cy: polar.cy,
  65757. r: radiusExtent[getRadiusIdx(polar)]
  65758. },
  65759. style: lineStyleModel.getLineStyle(),
  65760. z2: 1,
  65761. silent: true
  65762. });
  65763. circle.style.fill = null;
  65764. this.group.add(circle);
  65765. },
  65766. /**
  65767. * @private
  65768. */
  65769. _axisTick: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  65770. var tickModel = angleAxisModel.getModel('axisTick');
  65771. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  65772. var radius = radiusExtent[getRadiusIdx(polar)];
  65773. var lines = map(ticksAngles, function (tickAngleItem) {
  65774. return new Line({
  65775. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  65776. });
  65777. });
  65778. this.group.add(mergePath(
  65779. lines, {
  65780. style: defaults(
  65781. tickModel.getModel('lineStyle').getLineStyle(),
  65782. {
  65783. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  65784. }
  65785. )
  65786. }
  65787. ));
  65788. },
  65789. /**
  65790. * @private
  65791. */
  65792. _axisLabel: function (angleAxisModel, polar, ticksAngles, radiusExtent, labels) {
  65793. var rawCategoryData = angleAxisModel.getCategories(true);
  65794. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  65795. var labelMargin = commonLabelModel.get('margin');
  65796. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  65797. each$1(labels, function (labelItem, idx) {
  65798. var labelModel = commonLabelModel;
  65799. var tickValue = labelItem.tickValue;
  65800. var r = radiusExtent[getRadiusIdx(polar)];
  65801. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  65802. var cx = polar.cx;
  65803. var cy = polar.cy;
  65804. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  65805. ? 'center' : (p[0] > cx ? 'left' : 'right');
  65806. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  65807. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  65808. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  65809. labelModel = new Model(
  65810. rawCategoryData[tickValue].textStyle, commonLabelModel, commonLabelModel.ecModel
  65811. );
  65812. }
  65813. var textEl = new Text({silent: true});
  65814. this.group.add(textEl);
  65815. setTextStyle(textEl.style, labelModel, {
  65816. x: p[0],
  65817. y: p[1],
  65818. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  65819. text: labelItem.formattedLabel,
  65820. textAlign: labelTextAlign,
  65821. textVerticalAlign: labelTextVerticalAlign
  65822. });
  65823. }, this);
  65824. },
  65825. /**
  65826. * @private
  65827. */
  65828. _splitLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  65829. var splitLineModel = angleAxisModel.getModel('splitLine');
  65830. var lineStyleModel = splitLineModel.getModel('lineStyle');
  65831. var lineColors = lineStyleModel.get('color');
  65832. var lineCount = 0;
  65833. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  65834. var splitLines = [];
  65835. for (var i = 0; i < ticksAngles.length; i++) {
  65836. var colorIndex = (lineCount++) % lineColors.length;
  65837. splitLines[colorIndex] = splitLines[colorIndex] || [];
  65838. splitLines[colorIndex].push(new Line({
  65839. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  65840. }));
  65841. }
  65842. // Simple optimization
  65843. // Batching the lines if color are the same
  65844. for (var i = 0; i < splitLines.length; i++) {
  65845. this.group.add(mergePath(splitLines[i], {
  65846. style: defaults({
  65847. stroke: lineColors[i % lineColors.length]
  65848. }, lineStyleModel.getLineStyle()),
  65849. silent: true,
  65850. z: angleAxisModel.get('z')
  65851. }));
  65852. }
  65853. },
  65854. /**
  65855. * @private
  65856. */
  65857. _splitArea: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  65858. if (!ticksAngles.length) {
  65859. return;
  65860. }
  65861. var splitAreaModel = angleAxisModel.getModel('splitArea');
  65862. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  65863. var areaColors = areaStyleModel.get('color');
  65864. var lineCount = 0;
  65865. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  65866. var splitAreas = [];
  65867. var RADIAN = Math.PI / 180;
  65868. var prevAngle = -ticksAngles[0].coord * RADIAN;
  65869. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  65870. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  65871. var clockwise = angleAxisModel.get('clockwise');
  65872. for (var i = 1; i < ticksAngles.length; i++) {
  65873. var colorIndex = (lineCount++) % areaColors.length;
  65874. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  65875. splitAreas[colorIndex].push(new Sector({
  65876. shape: {
  65877. cx: polar.cx,
  65878. cy: polar.cy,
  65879. r0: r0,
  65880. r: r1,
  65881. startAngle: prevAngle,
  65882. endAngle: -ticksAngles[i].coord * RADIAN,
  65883. clockwise: clockwise
  65884. },
  65885. silent: true
  65886. }));
  65887. prevAngle = -ticksAngles[i].coord * RADIAN;
  65888. }
  65889. // Simple optimization
  65890. // Batching the lines if color are the same
  65891. for (var i = 0; i < splitAreas.length; i++) {
  65892. this.group.add(mergePath(splitAreas[i], {
  65893. style: defaults({
  65894. fill: areaColors[i % areaColors.length]
  65895. }, areaStyleModel.getAreaStyle()),
  65896. silent: true
  65897. }));
  65898. }
  65899. }
  65900. });
  65901. /*
  65902. * Licensed to the Apache Software Foundation (ASF) under one
  65903. * or more contributor license agreements. See the NOTICE file
  65904. * distributed with this work for additional information
  65905. * regarding copyright ownership. The ASF licenses this file
  65906. * to you under the Apache License, Version 2.0 (the
  65907. * "License"); you may not use this file except in compliance
  65908. * with the License. You may obtain a copy of the License at
  65909. *
  65910. * http://www.apache.org/licenses/LICENSE-2.0
  65911. *
  65912. * Unless required by applicable law or agreed to in writing,
  65913. * software distributed under the License is distributed on an
  65914. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65915. * KIND, either express or implied. See the License for the
  65916. * specific language governing permissions and limitations
  65917. * under the License.
  65918. */
  65919. /*
  65920. * Licensed to the Apache Software Foundation (ASF) under one
  65921. * or more contributor license agreements. See the NOTICE file
  65922. * distributed with this work for additional information
  65923. * regarding copyright ownership. The ASF licenses this file
  65924. * to you under the Apache License, Version 2.0 (the
  65925. * "License"); you may not use this file except in compliance
  65926. * with the License. You may obtain a copy of the License at
  65927. *
  65928. * http://www.apache.org/licenses/LICENSE-2.0
  65929. *
  65930. * Unless required by applicable law or agreed to in writing,
  65931. * software distributed under the License is distributed on an
  65932. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65933. * KIND, either express or implied. See the License for the
  65934. * specific language governing permissions and limitations
  65935. * under the License.
  65936. */
  65937. var axisBuilderAttrs$3 = [
  65938. 'axisLine', 'axisTickLabel', 'axisName'
  65939. ];
  65940. var selfBuilderAttrs$1 = [
  65941. 'splitLine', 'splitArea'
  65942. ];
  65943. AxisView.extend({
  65944. type: 'radiusAxis',
  65945. axisPointerClass: 'PolarAxisPointer',
  65946. render: function (radiusAxisModel, ecModel) {
  65947. this.group.removeAll();
  65948. if (!radiusAxisModel.get('show')) {
  65949. return;
  65950. }
  65951. var radiusAxis = radiusAxisModel.axis;
  65952. var polar = radiusAxis.polar;
  65953. var angleAxis = polar.getAngleAxis();
  65954. var ticksCoords = radiusAxis.getTicksCoords();
  65955. var axisAngle = angleAxis.getExtent()[0];
  65956. var radiusExtent = radiusAxis.getExtent();
  65957. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  65958. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  65959. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  65960. this.group.add(axisBuilder.getGroup());
  65961. each$1(selfBuilderAttrs$1, function (name) {
  65962. if (radiusAxisModel.get(name + '.show') && !radiusAxis.scale.isBlank()) {
  65963. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords);
  65964. }
  65965. }, this);
  65966. },
  65967. /**
  65968. * @private
  65969. */
  65970. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  65971. var splitLineModel = radiusAxisModel.getModel('splitLine');
  65972. var lineStyleModel = splitLineModel.getModel('lineStyle');
  65973. var lineColors = lineStyleModel.get('color');
  65974. var lineCount = 0;
  65975. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  65976. var splitLines = [];
  65977. for (var i = 0; i < ticksCoords.length; i++) {
  65978. var colorIndex = (lineCount++) % lineColors.length;
  65979. splitLines[colorIndex] = splitLines[colorIndex] || [];
  65980. splitLines[colorIndex].push(new Circle({
  65981. shape: {
  65982. cx: polar.cx,
  65983. cy: polar.cy,
  65984. r: ticksCoords[i].coord
  65985. },
  65986. silent: true
  65987. }));
  65988. }
  65989. // Simple optimization
  65990. // Batching the lines if color are the same
  65991. for (var i = 0; i < splitLines.length; i++) {
  65992. this.group.add(mergePath(splitLines[i], {
  65993. style: defaults({
  65994. stroke: lineColors[i % lineColors.length],
  65995. fill: null
  65996. }, lineStyleModel.getLineStyle()),
  65997. silent: true
  65998. }));
  65999. }
  66000. },
  66001. /**
  66002. * @private
  66003. */
  66004. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  66005. if (!ticksCoords.length) {
  66006. return;
  66007. }
  66008. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  66009. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  66010. var areaColors = areaStyleModel.get('color');
  66011. var lineCount = 0;
  66012. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  66013. var splitAreas = [];
  66014. var prevRadius = ticksCoords[0].coord;
  66015. for (var i = 1; i < ticksCoords.length; i++) {
  66016. var colorIndex = (lineCount++) % areaColors.length;
  66017. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  66018. splitAreas[colorIndex].push(new Sector({
  66019. shape: {
  66020. cx: polar.cx,
  66021. cy: polar.cy,
  66022. r0: prevRadius,
  66023. r: ticksCoords[i].coord,
  66024. startAngle: 0,
  66025. endAngle: Math.PI * 2
  66026. },
  66027. silent: true
  66028. }));
  66029. prevRadius = ticksCoords[i].coord;
  66030. }
  66031. // Simple optimization
  66032. // Batching the lines if color are the same
  66033. for (var i = 0; i < splitAreas.length; i++) {
  66034. this.group.add(mergePath(splitAreas[i], {
  66035. style: defaults({
  66036. fill: areaColors[i % areaColors.length]
  66037. }, areaStyleModel.getAreaStyle()),
  66038. silent: true
  66039. }));
  66040. }
  66041. }
  66042. });
  66043. /**
  66044. * @inner
  66045. */
  66046. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  66047. return {
  66048. position: [polar.cx, polar.cy],
  66049. rotation: axisAngle / 180 * Math.PI,
  66050. labelDirection: -1,
  66051. tickDirection: -1,
  66052. nameDirection: 1,
  66053. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  66054. // Over splitLine and splitArea
  66055. z2: 1
  66056. };
  66057. }
  66058. /*
  66059. * Licensed to the Apache Software Foundation (ASF) under one
  66060. * or more contributor license agreements. See the NOTICE file
  66061. * distributed with this work for additional information
  66062. * regarding copyright ownership. The ASF licenses this file
  66063. * to you under the Apache License, Version 2.0 (the
  66064. * "License"); you may not use this file except in compliance
  66065. * with the License. You may obtain a copy of the License at
  66066. *
  66067. * http://www.apache.org/licenses/LICENSE-2.0
  66068. *
  66069. * Unless required by applicable law or agreed to in writing,
  66070. * software distributed under the License is distributed on an
  66071. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66072. * KIND, either express or implied. See the License for the
  66073. * specific language governing permissions and limitations
  66074. * under the License.
  66075. */
  66076. /*
  66077. * Licensed to the Apache Software Foundation (ASF) under one
  66078. * or more contributor license agreements. See the NOTICE file
  66079. * distributed with this work for additional information
  66080. * regarding copyright ownership. The ASF licenses this file
  66081. * to you under the Apache License, Version 2.0 (the
  66082. * "License"); you may not use this file except in compliance
  66083. * with the License. You may obtain a copy of the License at
  66084. *
  66085. * http://www.apache.org/licenses/LICENSE-2.0
  66086. *
  66087. * Unless required by applicable law or agreed to in writing,
  66088. * software distributed under the License is distributed on an
  66089. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66090. * KIND, either express or implied. See the License for the
  66091. * specific language governing permissions and limitations
  66092. * under the License.
  66093. */
  66094. var PolarAxisPointer = BaseAxisPointer.extend({
  66095. /**
  66096. * @override
  66097. */
  66098. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  66099. var axis = axisModel.axis;
  66100. if (axis.dim === 'angle') {
  66101. this.animationThreshold = Math.PI / 18;
  66102. }
  66103. var polar = axis.polar;
  66104. var otherAxis = polar.getOtherAxis(axis);
  66105. var otherExtent = otherAxis.getExtent();
  66106. var coordValue;
  66107. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  66108. var axisPointerType = axisPointerModel.get('type');
  66109. if (axisPointerType && axisPointerType !== 'none') {
  66110. var elStyle = buildElStyle(axisPointerModel);
  66111. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  66112. axis, polar, coordValue, otherExtent, elStyle
  66113. );
  66114. pointerOption.style = elStyle;
  66115. elOption.graphicKey = pointerOption.type;
  66116. elOption.pointer = pointerOption;
  66117. }
  66118. var labelMargin = axisPointerModel.get('label.margin');
  66119. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  66120. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  66121. }
  66122. // Do not support handle, utill any user requires it.
  66123. });
  66124. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  66125. var axis = axisModel.axis;
  66126. var coord = axis.dataToCoord(value);
  66127. var axisAngle = polar.getAngleAxis().getExtent()[0];
  66128. axisAngle = axisAngle / 180 * Math.PI;
  66129. var radiusExtent = polar.getRadiusAxis().getExtent();
  66130. var position;
  66131. var align;
  66132. var verticalAlign;
  66133. if (axis.dim === 'radius') {
  66134. var transform = create$1();
  66135. rotate(transform, transform, axisAngle);
  66136. translate(transform, transform, [polar.cx, polar.cy]);
  66137. position = applyTransform$1([coord, -labelMargin], transform);
  66138. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  66139. var labelLayout = AxisBuilder.innerTextLayout(
  66140. axisAngle, labelRotation * Math.PI / 180, -1
  66141. );
  66142. align = labelLayout.textAlign;
  66143. verticalAlign = labelLayout.textVerticalAlign;
  66144. }
  66145. else { // angle axis
  66146. var r = radiusExtent[1];
  66147. position = polar.coordToPoint([r + labelMargin, coord]);
  66148. var cx = polar.cx;
  66149. var cy = polar.cy;
  66150. align = Math.abs(position[0] - cx) / r < 0.3
  66151. ? 'center' : (position[0] > cx ? 'left' : 'right');
  66152. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  66153. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  66154. }
  66155. return {
  66156. position: position,
  66157. align: align,
  66158. verticalAlign: verticalAlign
  66159. };
  66160. }
  66161. var pointerShapeBuilder$2 = {
  66162. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  66163. return axis.dim === 'angle'
  66164. ? {
  66165. type: 'Line',
  66166. shape: makeLineShape(
  66167. polar.coordToPoint([otherExtent[0], coordValue]),
  66168. polar.coordToPoint([otherExtent[1], coordValue])
  66169. )
  66170. }
  66171. : {
  66172. type: 'Circle',
  66173. shape: {
  66174. cx: polar.cx,
  66175. cy: polar.cy,
  66176. r: coordValue
  66177. }
  66178. };
  66179. },
  66180. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  66181. var bandWidth = Math.max(1, axis.getBandWidth());
  66182. var radian = Math.PI / 180;
  66183. return axis.dim === 'angle'
  66184. ? {
  66185. type: 'Sector',
  66186. shape: makeSectorShape(
  66187. polar.cx, polar.cy,
  66188. otherExtent[0], otherExtent[1],
  66189. // In ECharts y is negative if angle is positive
  66190. (-coordValue - bandWidth / 2) * radian,
  66191. (-coordValue + bandWidth / 2) * radian
  66192. )
  66193. }
  66194. : {
  66195. type: 'Sector',
  66196. shape: makeSectorShape(
  66197. polar.cx, polar.cy,
  66198. coordValue - bandWidth / 2,
  66199. coordValue + bandWidth / 2,
  66200. 0, Math.PI * 2
  66201. )
  66202. };
  66203. }
  66204. };
  66205. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  66206. /*
  66207. * Licensed to the Apache Software Foundation (ASF) under one
  66208. * or more contributor license agreements. See the NOTICE file
  66209. * distributed with this work for additional information
  66210. * regarding copyright ownership. The ASF licenses this file
  66211. * to you under the Apache License, Version 2.0 (the
  66212. * "License"); you may not use this file except in compliance
  66213. * with the License. You may obtain a copy of the License at
  66214. *
  66215. * http://www.apache.org/licenses/LICENSE-2.0
  66216. *
  66217. * Unless required by applicable law or agreed to in writing,
  66218. * software distributed under the License is distributed on an
  66219. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66220. * KIND, either express or implied. See the License for the
  66221. * specific language governing permissions and limitations
  66222. * under the License.
  66223. */
  66224. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  66225. registerLayout(curry(barLayoutPolar, 'bar'));
  66226. // Polar view
  66227. extendComponentView({
  66228. type: 'polar'
  66229. });
  66230. /*
  66231. * Licensed to the Apache Software Foundation (ASF) under one
  66232. * or more contributor license agreements. See the NOTICE file
  66233. * distributed with this work for additional information
  66234. * regarding copyright ownership. The ASF licenses this file
  66235. * to you under the Apache License, Version 2.0 (the
  66236. * "License"); you may not use this file except in compliance
  66237. * with the License. You may obtain a copy of the License at
  66238. *
  66239. * http://www.apache.org/licenses/LICENSE-2.0
  66240. *
  66241. * Unless required by applicable law or agreed to in writing,
  66242. * software distributed under the License is distributed on an
  66243. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66244. * KIND, either express or implied. See the License for the
  66245. * specific language governing permissions and limitations
  66246. * under the License.
  66247. */
  66248. var GeoModel = ComponentModel.extend({
  66249. type: 'geo',
  66250. /**
  66251. * @type {module:echarts/coord/geo/Geo}
  66252. */
  66253. coordinateSystem: null,
  66254. layoutMode: 'box',
  66255. init: function (option) {
  66256. ComponentModel.prototype.init.apply(this, arguments);
  66257. // Default label emphasis `show`
  66258. defaultEmphasis(option, 'label', ['show']);
  66259. },
  66260. optionUpdated: function () {
  66261. var option = this.option;
  66262. var self = this;
  66263. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  66264. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  66265. if (regionOpt.name) {
  66266. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  66267. }
  66268. return optionModelMap;
  66269. }, createHashMap());
  66270. this.updateSelectedMap(option.regions);
  66271. },
  66272. defaultOption: {
  66273. zlevel: 0,
  66274. z: 0,
  66275. show: true,
  66276. left: 'center',
  66277. top: 'center',
  66278. // width:,
  66279. // height:,
  66280. // right
  66281. // bottom
  66282. // Aspect is width / height. Inited to be geoJson bbox aspect
  66283. // This parameter is used for scale this aspect
  66284. // If svg used, aspectScale is 1 by default.
  66285. // aspectScale: 0.75,
  66286. aspectScale: null,
  66287. ///// Layout with center and size
  66288. // If you wan't to put map in a fixed size box with right aspect ratio
  66289. // This two properties may more conveninet
  66290. // layoutCenter: [50%, 50%]
  66291. // layoutSize: 100
  66292. silent: false,
  66293. // Map type
  66294. map: '',
  66295. // Define left-top, right-bottom coords to control view
  66296. // For example, [ [180, 90], [-180, -90] ]
  66297. boundingCoords: null,
  66298. // Default on center of map
  66299. center: null,
  66300. zoom: 1,
  66301. scaleLimit: null,
  66302. // selectedMode: false
  66303. label: {
  66304. show: false,
  66305. color: '#000'
  66306. },
  66307. itemStyle: {
  66308. // color: 各异,
  66309. borderWidth: 0.5,
  66310. borderColor: '#444',
  66311. color: '#eee'
  66312. },
  66313. emphasis: {
  66314. label: {
  66315. show: true,
  66316. color: 'rgb(100,0,0)'
  66317. },
  66318. itemStyle: {
  66319. color: 'rgba(255,215,0,0.8)'
  66320. }
  66321. },
  66322. regions: []
  66323. },
  66324. /**
  66325. * Get model of region
  66326. * @param {string} name
  66327. * @return {module:echarts/model/Model}
  66328. */
  66329. getRegionModel: function (name) {
  66330. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  66331. },
  66332. /**
  66333. * Format label
  66334. * @param {string} name Region name
  66335. * @param {string} [status='normal'] 'normal' or 'emphasis'
  66336. * @return {string}
  66337. */
  66338. getFormattedLabel: function (name, status) {
  66339. var regionModel = this.getRegionModel(name);
  66340. var formatter = regionModel.get('label.' + status + '.formatter');
  66341. var params = {
  66342. name: name
  66343. };
  66344. if (typeof formatter === 'function') {
  66345. params.status = status;
  66346. return formatter(params);
  66347. }
  66348. else if (typeof formatter === 'string') {
  66349. return formatter.replace('{a}', name != null ? name : '');
  66350. }
  66351. },
  66352. setZoom: function (zoom) {
  66353. this.option.zoom = zoom;
  66354. },
  66355. setCenter: function (center) {
  66356. this.option.center = center;
  66357. }
  66358. });
  66359. mixin(GeoModel, selectableMixin);
  66360. /*
  66361. * Licensed to the Apache Software Foundation (ASF) under one
  66362. * or more contributor license agreements. See the NOTICE file
  66363. * distributed with this work for additional information
  66364. * regarding copyright ownership. The ASF licenses this file
  66365. * to you under the Apache License, Version 2.0 (the
  66366. * "License"); you may not use this file except in compliance
  66367. * with the License. You may obtain a copy of the License at
  66368. *
  66369. * http://www.apache.org/licenses/LICENSE-2.0
  66370. *
  66371. * Unless required by applicable law or agreed to in writing,
  66372. * software distributed under the License is distributed on an
  66373. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66374. * KIND, either express or implied. See the License for the
  66375. * specific language governing permissions and limitations
  66376. * under the License.
  66377. */
  66378. extendComponentView({
  66379. type: 'geo',
  66380. init: function (ecModel, api) {
  66381. var mapDraw = new MapDraw(api, true);
  66382. this._mapDraw = mapDraw;
  66383. this.group.add(mapDraw.group);
  66384. },
  66385. render: function (geoModel, ecModel, api, payload) {
  66386. // Not render if it is an toggleSelect action from self
  66387. if (payload && payload.type === 'geoToggleSelect'
  66388. && payload.from === this.uid
  66389. ) {
  66390. return;
  66391. }
  66392. var mapDraw = this._mapDraw;
  66393. if (geoModel.get('show')) {
  66394. mapDraw.draw(geoModel, ecModel, api, this, payload);
  66395. }
  66396. else {
  66397. this._mapDraw.group.removeAll();
  66398. }
  66399. this.group.silent = geoModel.get('silent');
  66400. },
  66401. dispose: function () {
  66402. this._mapDraw && this._mapDraw.remove();
  66403. }
  66404. });
  66405. /*
  66406. * Licensed to the Apache Software Foundation (ASF) under one
  66407. * or more contributor license agreements. See the NOTICE file
  66408. * distributed with this work for additional information
  66409. * regarding copyright ownership. The ASF licenses this file
  66410. * to you under the Apache License, Version 2.0 (the
  66411. * "License"); you may not use this file except in compliance
  66412. * with the License. You may obtain a copy of the License at
  66413. *
  66414. * http://www.apache.org/licenses/LICENSE-2.0
  66415. *
  66416. * Unless required by applicable law or agreed to in writing,
  66417. * software distributed under the License is distributed on an
  66418. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66419. * KIND, either express or implied. See the License for the
  66420. * specific language governing permissions and limitations
  66421. * under the License.
  66422. */
  66423. function makeAction(method, actionInfo) {
  66424. actionInfo.update = 'updateView';
  66425. registerAction(actionInfo, function (payload, ecModel) {
  66426. var selected = {};
  66427. ecModel.eachComponent(
  66428. { mainType: 'geo', query: payload},
  66429. function (geoModel) {
  66430. geoModel[method](payload.name);
  66431. var geo = geoModel.coordinateSystem;
  66432. each$1(geo.regions, function (region) {
  66433. selected[region.name] = geoModel.isSelected(region.name) || false;
  66434. });
  66435. }
  66436. );
  66437. return {
  66438. selected: selected,
  66439. name: payload.name
  66440. };
  66441. });
  66442. }
  66443. makeAction('toggleSelected', {
  66444. type: 'geoToggleSelect',
  66445. event: 'geoselectchanged'
  66446. });
  66447. makeAction('select', {
  66448. type: 'geoSelect',
  66449. event: 'geoselected'
  66450. });
  66451. makeAction('unSelect', {
  66452. type: 'geoUnSelect',
  66453. event: 'geounselected'
  66454. });
  66455. /*
  66456. * Licensed to the Apache Software Foundation (ASF) under one
  66457. * or more contributor license agreements. See the NOTICE file
  66458. * distributed with this work for additional information
  66459. * regarding copyright ownership. The ASF licenses this file
  66460. * to you under the Apache License, Version 2.0 (the
  66461. * "License"); you may not use this file except in compliance
  66462. * with the License. You may obtain a copy of the License at
  66463. *
  66464. * http://www.apache.org/licenses/LICENSE-2.0
  66465. *
  66466. * Unless required by applicable law or agreed to in writing,
  66467. * software distributed under the License is distributed on an
  66468. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66469. * KIND, either express or implied. See the License for the
  66470. * specific language governing permissions and limitations
  66471. * under the License.
  66472. */
  66473. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  66474. var preprocessor$1 = function (option, isNew) {
  66475. var brushComponents = option && option.brush;
  66476. if (!isArray(brushComponents)) {
  66477. brushComponents = brushComponents ? [brushComponents] : [];
  66478. }
  66479. if (!brushComponents.length) {
  66480. return;
  66481. }
  66482. var brushComponentSpecifiedBtns = [];
  66483. each$1(brushComponents, function (brushOpt) {
  66484. var tbs = brushOpt.hasOwnProperty('toolbox')
  66485. ? brushOpt.toolbox : [];
  66486. if (tbs instanceof Array) {
  66487. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  66488. }
  66489. });
  66490. var toolbox = option && option.toolbox;
  66491. if (isArray(toolbox)) {
  66492. toolbox = toolbox[0];
  66493. }
  66494. if (!toolbox) {
  66495. toolbox = {feature: {}};
  66496. option.toolbox = [toolbox];
  66497. }
  66498. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  66499. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  66500. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  66501. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  66502. removeDuplicate(brushTypes);
  66503. if (isNew && !brushTypes.length) {
  66504. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  66505. }
  66506. };
  66507. function removeDuplicate(arr) {
  66508. var map$$1 = {};
  66509. each$1(arr, function (val) {
  66510. map$$1[val] = 1;
  66511. });
  66512. arr.length = 0;
  66513. each$1(map$$1, function (flag, val) {
  66514. arr.push(val);
  66515. });
  66516. }
  66517. /*
  66518. * Licensed to the Apache Software Foundation (ASF) under one
  66519. * or more contributor license agreements. See the NOTICE file
  66520. * distributed with this work for additional information
  66521. * regarding copyright ownership. The ASF licenses this file
  66522. * to you under the Apache License, Version 2.0 (the
  66523. * "License"); you may not use this file except in compliance
  66524. * with the License. You may obtain a copy of the License at
  66525. *
  66526. * http://www.apache.org/licenses/LICENSE-2.0
  66527. *
  66528. * Unless required by applicable law or agreed to in writing,
  66529. * software distributed under the License is distributed on an
  66530. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66531. * KIND, either express or implied. See the License for the
  66532. * specific language governing permissions and limitations
  66533. * under the License.
  66534. */
  66535. /**
  66536. * @file Visual solution, for consistent option specification.
  66537. */
  66538. var each$19 = each$1;
  66539. function hasKeys(obj) {
  66540. if (obj) {
  66541. for (var name in obj) {
  66542. if (obj.hasOwnProperty(name)) {
  66543. return true;
  66544. }
  66545. }
  66546. }
  66547. }
  66548. /**
  66549. * @param {Object} option
  66550. * @param {Array.<string>} stateList
  66551. * @param {Function} [supplementVisualOption]
  66552. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  66553. */
  66554. function createVisualMappings(option, stateList, supplementVisualOption) {
  66555. var visualMappings = {};
  66556. each$19(stateList, function (state) {
  66557. var mappings = visualMappings[state] = createMappings();
  66558. each$19(option[state], function (visualData, visualType) {
  66559. if (!VisualMapping.isValidType(visualType)) {
  66560. return;
  66561. }
  66562. var mappingOption = {
  66563. type: visualType,
  66564. visual: visualData
  66565. };
  66566. supplementVisualOption && supplementVisualOption(mappingOption, state);
  66567. mappings[visualType] = new VisualMapping(mappingOption);
  66568. // Prepare a alpha for opacity, for some case that opacity
  66569. // is not supported, such as rendering using gradient color.
  66570. if (visualType === 'opacity') {
  66571. mappingOption = clone(mappingOption);
  66572. mappingOption.type = 'colorAlpha';
  66573. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  66574. }
  66575. });
  66576. });
  66577. return visualMappings;
  66578. function createMappings() {
  66579. var Creater = function () {};
  66580. // Make sure hidden fields will not be visited by
  66581. // object iteration (with hasOwnProperty checking).
  66582. Creater.prototype.__hidden = Creater.prototype;
  66583. var obj = new Creater();
  66584. return obj;
  66585. }
  66586. }
  66587. /**
  66588. * @param {Object} thisOption
  66589. * @param {Object} newOption
  66590. * @param {Array.<string>} keys
  66591. */
  66592. function replaceVisualOption(thisOption, newOption, keys) {
  66593. // Visual attributes merge is not supported, otherwise it
  66594. // brings overcomplicated merge logic. See #2853. So if
  66595. // newOption has anyone of these keys, all of these keys
  66596. // will be reset. Otherwise, all keys remain.
  66597. var has;
  66598. each$1(keys, function (key) {
  66599. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  66600. has = true;
  66601. }
  66602. });
  66603. has && each$1(keys, function (key) {
  66604. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  66605. thisOption[key] = clone(newOption[key]);
  66606. }
  66607. else {
  66608. delete thisOption[key];
  66609. }
  66610. });
  66611. }
  66612. /**
  66613. * @param {Array.<string>} stateList
  66614. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  66615. * @param {module:echarts/data/List} list
  66616. * @param {Function} getValueState param: valueOrIndex, return: state.
  66617. * @param {object} [scope] Scope for getValueState
  66618. * @param {string} [dimension] Concrete dimension, if used.
  66619. */
  66620. // ???! handle brush?
  66621. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  66622. var visualTypesMap = {};
  66623. each$1(stateList, function (state) {
  66624. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  66625. visualTypesMap[state] = visualTypes;
  66626. });
  66627. var dataIndex;
  66628. function getVisual(key) {
  66629. return data.getItemVisual(dataIndex, key);
  66630. }
  66631. function setVisual(key, value) {
  66632. data.setItemVisual(dataIndex, key, value);
  66633. }
  66634. if (dimension == null) {
  66635. data.each(eachItem);
  66636. }
  66637. else {
  66638. data.each([dimension], eachItem);
  66639. }
  66640. function eachItem(valueOrIndex, index) {
  66641. dataIndex = dimension == null ? valueOrIndex : index;
  66642. var rawDataItem = data.getRawDataItem(dataIndex);
  66643. // Consider performance
  66644. if (rawDataItem && rawDataItem.visualMap === false) {
  66645. return;
  66646. }
  66647. var valueState = getValueState.call(scope, valueOrIndex);
  66648. var mappings = visualMappings[valueState];
  66649. var visualTypes = visualTypesMap[valueState];
  66650. for (var i = 0, len = visualTypes.length; i < len; i++) {
  66651. var type = visualTypes[i];
  66652. mappings[type] && mappings[type].applyVisual(
  66653. valueOrIndex, getVisual, setVisual
  66654. );
  66655. }
  66656. }
  66657. }
  66658. /**
  66659. * @param {module:echarts/data/List} data
  66660. * @param {Array.<string>} stateList
  66661. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  66662. * @param {Function} getValueState param: valueOrIndex, return: state.
  66663. * @param {number} [dim] dimension or dimension index.
  66664. */
  66665. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  66666. var visualTypesMap = {};
  66667. each$1(stateList, function (state) {
  66668. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  66669. visualTypesMap[state] = visualTypes;
  66670. });
  66671. function progress(params, data) {
  66672. if (dim != null) {
  66673. dim = data.getDimension(dim);
  66674. }
  66675. function getVisual(key) {
  66676. return data.getItemVisual(dataIndex, key);
  66677. }
  66678. function setVisual(key, value) {
  66679. data.setItemVisual(dataIndex, key, value);
  66680. }
  66681. var dataIndex;
  66682. while ((dataIndex = params.next()) != null) {
  66683. var rawDataItem = data.getRawDataItem(dataIndex);
  66684. // Consider performance
  66685. if (rawDataItem && rawDataItem.visualMap === false) {
  66686. continue;
  66687. }
  66688. var value = dim != null
  66689. ? data.get(dim, dataIndex, true)
  66690. : dataIndex;
  66691. var valueState = getValueState(value);
  66692. var mappings = visualMappings[valueState];
  66693. var visualTypes = visualTypesMap[valueState];
  66694. for (var i = 0, len = visualTypes.length; i < len; i++) {
  66695. var type = visualTypes[i];
  66696. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  66697. }
  66698. }
  66699. }
  66700. return {progress: progress};
  66701. }
  66702. /*
  66703. * Licensed to the Apache Software Foundation (ASF) under one
  66704. * or more contributor license agreements. See the NOTICE file
  66705. * distributed with this work for additional information
  66706. * regarding copyright ownership. The ASF licenses this file
  66707. * to you under the Apache License, Version 2.0 (the
  66708. * "License"); you may not use this file except in compliance
  66709. * with the License. You may obtain a copy of the License at
  66710. *
  66711. * http://www.apache.org/licenses/LICENSE-2.0
  66712. *
  66713. * Unless required by applicable law or agreed to in writing,
  66714. * software distributed under the License is distributed on an
  66715. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66716. * KIND, either express or implied. See the License for the
  66717. * specific language governing permissions and limitations
  66718. * under the License.
  66719. */
  66720. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  66721. // Key of the second level is chart element type: `point`, `rect`.
  66722. // See moudule:echarts/component/helper/BrushController
  66723. // function param:
  66724. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  66725. // {Object} selectors {point: selector, rect: selector, ...}
  66726. // {Object} area {range: [[], [], ..], boudingRect}
  66727. // function return:
  66728. // {boolean} Whether in the given brush.
  66729. var selector = {
  66730. lineX: getLineSelectors(0),
  66731. lineY: getLineSelectors(1),
  66732. rect: {
  66733. point: function (itemLayout, selectors, area) {
  66734. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  66735. },
  66736. rect: function (itemLayout, selectors, area) {
  66737. return itemLayout && area.boundingRect.intersect(itemLayout);
  66738. }
  66739. },
  66740. polygon: {
  66741. point: function (itemLayout, selectors, area) {
  66742. return itemLayout
  66743. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  66744. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  66745. },
  66746. rect: function (itemLayout, selectors, area) {
  66747. var points = area.range;
  66748. if (!itemLayout || points.length <= 1) {
  66749. return false;
  66750. }
  66751. var x = itemLayout.x;
  66752. var y = itemLayout.y;
  66753. var width = itemLayout.width;
  66754. var height = itemLayout.height;
  66755. var p = points[0];
  66756. if (contain$1(points, x, y)
  66757. || contain$1(points, x + width, y)
  66758. || contain$1(points, x, y + height)
  66759. || contain$1(points, x + width, y + height)
  66760. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  66761. || lineIntersectPolygon(x, y, x + width, y, points)
  66762. || lineIntersectPolygon(x, y, x, y + height, points)
  66763. || lineIntersectPolygon(x + width, y, x + width, y + height, points)
  66764. || lineIntersectPolygon(x, y + height, x + width, y + height, points)
  66765. ) {
  66766. return true;
  66767. }
  66768. }
  66769. }
  66770. };
  66771. function getLineSelectors(xyIndex) {
  66772. var xy = ['x', 'y'];
  66773. var wh = ['width', 'height'];
  66774. return {
  66775. point: function (itemLayout, selectors, area) {
  66776. if (itemLayout) {
  66777. var range = area.range;
  66778. var p = itemLayout[xyIndex];
  66779. return inLineRange(p, range);
  66780. }
  66781. },
  66782. rect: function (itemLayout, selectors, area) {
  66783. if (itemLayout) {
  66784. var range = area.range;
  66785. var layoutRange = [
  66786. itemLayout[xy[xyIndex]],
  66787. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  66788. ];
  66789. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  66790. return inLineRange(layoutRange[0], range)
  66791. || inLineRange(layoutRange[1], range)
  66792. || inLineRange(range[0], layoutRange)
  66793. || inLineRange(range[1], layoutRange);
  66794. }
  66795. }
  66796. };
  66797. }
  66798. function inLineRange(p, range) {
  66799. return range[0] <= p && p <= range[1];
  66800. }
  66801. function lineIntersectPolygon(lx, ly, l2x, l2y, points) {
  66802. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  66803. var p = points[i];
  66804. if (lineIntersect(lx, ly, l2x, l2y, p[0], p[1], p2[0], p2[1])) {
  66805. return true;
  66806. }
  66807. p2 = p;
  66808. }
  66809. }
  66810. // Code from <http://blog.csdn.net/rickliuxiao/article/details/6259322> with some fix.
  66811. // See <https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection>
  66812. function lineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  66813. var delta = determinant(a2x - a1x, b1x - b2x, a2y - a1y, b1y - b2y);
  66814. if (nearZero(delta)) { // parallel
  66815. return false;
  66816. }
  66817. var namenda = determinant(b1x - a1x, b1x - b2x, b1y - a1y, b1y - b2y) / delta;
  66818. if (namenda < 0 || namenda > 1) {
  66819. return false;
  66820. }
  66821. var miu = determinant(a2x - a1x, b1x - a1x, a2y - a1y, b1y - a1y) / delta;
  66822. if (miu < 0 || miu > 1) {
  66823. return false;
  66824. }
  66825. return true;
  66826. }
  66827. function nearZero(val) {
  66828. return val <= (1e-6) && val >= -(1e-6);
  66829. }
  66830. function determinant(v1, v2, v3, v4) {
  66831. return v1 * v4 - v2 * v3;
  66832. }
  66833. /*
  66834. * Licensed to the Apache Software Foundation (ASF) under one
  66835. * or more contributor license agreements. See the NOTICE file
  66836. * distributed with this work for additional information
  66837. * regarding copyright ownership. The ASF licenses this file
  66838. * to you under the Apache License, Version 2.0 (the
  66839. * "License"); you may not use this file except in compliance
  66840. * with the License. You may obtain a copy of the License at
  66841. *
  66842. * http://www.apache.org/licenses/LICENSE-2.0
  66843. *
  66844. * Unless required by applicable law or agreed to in writing,
  66845. * software distributed under the License is distributed on an
  66846. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66847. * KIND, either express or implied. See the License for the
  66848. * specific language governing permissions and limitations
  66849. * under the License.
  66850. */
  66851. var each$20 = each$1;
  66852. var indexOf$1 = indexOf;
  66853. var curry$5 = curry;
  66854. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  66855. // FIXME
  66856. // how to genarialize to more coordinate systems.
  66857. var INCLUDE_FINDER_MAIN_TYPES = [
  66858. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  66859. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  66860. ];
  66861. /**
  66862. * [option in constructor]:
  66863. * {
  66864. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  66865. * }
  66866. *
  66867. *
  66868. * [targetInfo]:
  66869. *
  66870. * There can be multiple axes in a single targetInfo. Consider the case
  66871. * of `grid` component, a targetInfo represents a grid which contains one or more
  66872. * cartesian and one or more axes. And consider the case of parallel system,
  66873. * which has multiple axes in a coordinate system.
  66874. * Can be {
  66875. * panelId: ...,
  66876. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  66877. * coordSyses: all cartesians.
  66878. * gridModel: <grid component>
  66879. * xAxes: correspond to coordSyses on index
  66880. * yAxes: correspond to coordSyses on index
  66881. * }
  66882. * or {
  66883. * panelId: ...,
  66884. * coordSys: <geo coord sys>
  66885. * coordSyses: [<geo coord sys>]
  66886. * geoModel: <geo component>
  66887. * }
  66888. *
  66889. *
  66890. * [panelOpt]:
  66891. *
  66892. * Make from targetInfo. Input to BrushController.
  66893. * {
  66894. * panelId: ...,
  66895. * rect: ...
  66896. * }
  66897. *
  66898. *
  66899. * [area]:
  66900. *
  66901. * Generated by BrushController or user input.
  66902. * {
  66903. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  66904. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  66905. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  66906. * range: pixel range.
  66907. * coordRange: representitive coord range (the first one of coordRanges).
  66908. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  66909. * }
  66910. */
  66911. /**
  66912. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  66913. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  66914. * @param {module:echarts/model/Global} ecModel
  66915. * @param {Object} [opt]
  66916. * @param {Array.<string>} [opt.include] include coordinate system types.
  66917. */
  66918. function BrushTargetManager(option, ecModel, opt) {
  66919. /**
  66920. * @private
  66921. * @type {Array.<Object>}
  66922. */
  66923. var targetInfoList = this._targetInfoList = [];
  66924. var info = {};
  66925. var foundCpts = parseFinder$1(ecModel, option);
  66926. each$20(targetInfoBuilders, function (builder, type) {
  66927. if (!opt || !opt.include || indexOf$1(opt.include, type) >= 0) {
  66928. builder(foundCpts, targetInfoList, info);
  66929. }
  66930. });
  66931. }
  66932. var proto$2 = BrushTargetManager.prototype;
  66933. proto$2.setOutputRanges = function (areas, ecModel) {
  66934. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  66935. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  66936. // area.coordRange is the first of area.coordRanges
  66937. if (!area.coordRange) {
  66938. area.coordRange = coordRange;
  66939. // In 'category' axis, coord to pixel is not reversible, so we can not
  66940. // rebuild range by coordRange accrately, which may bring trouble when
  66941. // brushing only one item. So we use __rangeOffset to rebuilding range
  66942. // by coordRange. And this it only used in brush component so it is no
  66943. // need to be adapted to coordRanges.
  66944. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  66945. area.__rangeOffset = {
  66946. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  66947. xyMinMax: result.xyMinMax
  66948. };
  66949. }
  66950. });
  66951. };
  66952. proto$2.matchOutputRanges = function (areas, ecModel, cb) {
  66953. each$20(areas, function (area) {
  66954. var targetInfo = this.findTargetInfo(area, ecModel);
  66955. if (targetInfo && targetInfo !== true) {
  66956. each$1(
  66957. targetInfo.coordSyses,
  66958. function (coordSys) {
  66959. var result = coordConvert[area.brushType](1, coordSys, area.range);
  66960. cb(area, result.values, coordSys, ecModel);
  66961. }
  66962. );
  66963. }
  66964. }, this);
  66965. };
  66966. proto$2.setInputRanges = function (areas, ecModel) {
  66967. each$20(areas, function (area) {
  66968. var targetInfo = this.findTargetInfo(area, ecModel);
  66969. if (__DEV__) {
  66970. assert$1(
  66971. !targetInfo || targetInfo === true || area.coordRange,
  66972. 'coordRange must be specified when coord index specified.'
  66973. );
  66974. assert$1(
  66975. !targetInfo || targetInfo !== true || area.range,
  66976. 'range must be specified in global brush.'
  66977. );
  66978. }
  66979. area.range = area.range || [];
  66980. // convert coordRange to global range and set panelId.
  66981. if (targetInfo && targetInfo !== true) {
  66982. area.panelId = targetInfo.panelId;
  66983. // (1) area.range shoule always be calculate from coordRange but does
  66984. // not keep its original value, for the sake of the dataZoom scenario,
  66985. // where area.coordRange remains unchanged but area.range may be changed.
  66986. // (2) Only support converting one coordRange to pixel range in brush
  66987. // component. So do not consider `coordRanges`.
  66988. // (3) About __rangeOffset, see comment above.
  66989. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  66990. var rangeOffset = area.__rangeOffset;
  66991. area.range = rangeOffset
  66992. ? diffProcessor[area.brushType](
  66993. result.values,
  66994. rangeOffset.offset,
  66995. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  66996. )
  66997. : result.values;
  66998. }
  66999. }, this);
  67000. };
  67001. proto$2.makePanelOpts = function (api, getDefaultBrushType) {
  67002. return map(this._targetInfoList, function (targetInfo) {
  67003. var rect = targetInfo.getPanelRect();
  67004. return {
  67005. panelId: targetInfo.panelId,
  67006. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  67007. clipPath: makeRectPanelClipPath(rect),
  67008. isTargetByCursor: makeRectIsTargetByCursor(
  67009. rect, api, targetInfo.coordSysModel
  67010. ),
  67011. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  67012. };
  67013. });
  67014. };
  67015. proto$2.controlSeries = function (area, seriesModel, ecModel) {
  67016. // Check whether area is bound in coord, and series do not belong to that coord.
  67017. // If do not do this check, some brush (like lineX) will controll all axes.
  67018. var targetInfo = this.findTargetInfo(area, ecModel);
  67019. return targetInfo === true || (
  67020. targetInfo && indexOf$1(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  67021. );
  67022. };
  67023. /**
  67024. * If return Object, a coord found.
  67025. * If reutrn true, global found.
  67026. * Otherwise nothing found.
  67027. *
  67028. * @param {Object} area
  67029. * @param {Array} targetInfoList
  67030. * @return {Object|boolean}
  67031. */
  67032. proto$2.findTargetInfo = function (area, ecModel) {
  67033. var targetInfoList = this._targetInfoList;
  67034. var foundCpts = parseFinder$1(ecModel, area);
  67035. for (var i = 0; i < targetInfoList.length; i++) {
  67036. var targetInfo = targetInfoList[i];
  67037. var areaPanelId = area.panelId;
  67038. if (areaPanelId) {
  67039. if (targetInfo.panelId === areaPanelId) {
  67040. return targetInfo;
  67041. }
  67042. }
  67043. else {
  67044. for (var i = 0; i < targetInfoMatchers.length; i++) {
  67045. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  67046. return targetInfo;
  67047. }
  67048. }
  67049. }
  67050. }
  67051. return true;
  67052. };
  67053. function formatMinMax(minMax) {
  67054. minMax[0] > minMax[1] && minMax.reverse();
  67055. return minMax;
  67056. }
  67057. function parseFinder$1(ecModel, option) {
  67058. return parseFinder(
  67059. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  67060. );
  67061. }
  67062. var targetInfoBuilders = {
  67063. grid: function (foundCpts, targetInfoList) {
  67064. var xAxisModels = foundCpts.xAxisModels;
  67065. var yAxisModels = foundCpts.yAxisModels;
  67066. var gridModels = foundCpts.gridModels;
  67067. // Remove duplicated.
  67068. var gridModelMap = createHashMap();
  67069. var xAxesHas = {};
  67070. var yAxesHas = {};
  67071. if (!xAxisModels && !yAxisModels && !gridModels) {
  67072. return;
  67073. }
  67074. each$20(xAxisModels, function (axisModel) {
  67075. var gridModel = axisModel.axis.grid.model;
  67076. gridModelMap.set(gridModel.id, gridModel);
  67077. xAxesHas[gridModel.id] = true;
  67078. });
  67079. each$20(yAxisModels, function (axisModel) {
  67080. var gridModel = axisModel.axis.grid.model;
  67081. gridModelMap.set(gridModel.id, gridModel);
  67082. yAxesHas[gridModel.id] = true;
  67083. });
  67084. each$20(gridModels, function (gridModel) {
  67085. gridModelMap.set(gridModel.id, gridModel);
  67086. xAxesHas[gridModel.id] = true;
  67087. yAxesHas[gridModel.id] = true;
  67088. });
  67089. gridModelMap.each(function (gridModel) {
  67090. var grid = gridModel.coordinateSystem;
  67091. var cartesians = [];
  67092. each$20(grid.getCartesians(), function (cartesian, index) {
  67093. if (indexOf$1(xAxisModels, cartesian.getAxis('x').model) >= 0
  67094. || indexOf$1(yAxisModels, cartesian.getAxis('y').model) >= 0
  67095. ) {
  67096. cartesians.push(cartesian);
  67097. }
  67098. });
  67099. targetInfoList.push({
  67100. panelId: 'grid--' + gridModel.id,
  67101. gridModel: gridModel,
  67102. coordSysModel: gridModel,
  67103. // Use the first one as the representitive coordSys.
  67104. coordSys: cartesians[0],
  67105. coordSyses: cartesians,
  67106. getPanelRect: panelRectBuilder.grid,
  67107. xAxisDeclared: xAxesHas[gridModel.id],
  67108. yAxisDeclared: yAxesHas[gridModel.id]
  67109. });
  67110. });
  67111. },
  67112. geo: function (foundCpts, targetInfoList) {
  67113. each$20(foundCpts.geoModels, function (geoModel) {
  67114. var coordSys = geoModel.coordinateSystem;
  67115. targetInfoList.push({
  67116. panelId: 'geo--' + geoModel.id,
  67117. geoModel: geoModel,
  67118. coordSysModel: geoModel,
  67119. coordSys: coordSys,
  67120. coordSyses: [coordSys],
  67121. getPanelRect: panelRectBuilder.geo
  67122. });
  67123. });
  67124. }
  67125. };
  67126. var targetInfoMatchers = [
  67127. // grid
  67128. function (foundCpts, targetInfo) {
  67129. var xAxisModel = foundCpts.xAxisModel;
  67130. var yAxisModel = foundCpts.yAxisModel;
  67131. var gridModel = foundCpts.gridModel;
  67132. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  67133. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  67134. return gridModel && gridModel === targetInfo.gridModel;
  67135. },
  67136. // geo
  67137. function (foundCpts, targetInfo) {
  67138. var geoModel = foundCpts.geoModel;
  67139. return geoModel && geoModel === targetInfo.geoModel;
  67140. }
  67141. ];
  67142. var panelRectBuilder = {
  67143. grid: function () {
  67144. // grid is not Transformable.
  67145. return this.coordSys.grid.getRect().clone();
  67146. },
  67147. geo: function () {
  67148. var coordSys = this.coordSys;
  67149. var rect = coordSys.getBoundingRect().clone();
  67150. // geo roam and zoom transform
  67151. rect.applyTransform(getTransform(coordSys));
  67152. return rect;
  67153. }
  67154. };
  67155. var coordConvert = {
  67156. lineX: curry$5(axisConvert, 0),
  67157. lineY: curry$5(axisConvert, 1),
  67158. rect: function (to, coordSys, rangeOrCoordRange) {
  67159. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  67160. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  67161. var values = [
  67162. formatMinMax([xminymin[0], xmaxymax[0]]),
  67163. formatMinMax([xminymin[1], xmaxymax[1]])
  67164. ];
  67165. return {values: values, xyMinMax: values};
  67166. },
  67167. polygon: function (to, coordSys, rangeOrCoordRange) {
  67168. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  67169. var values = map(rangeOrCoordRange, function (item) {
  67170. var p = coordSys[COORD_CONVERTS[to]](item);
  67171. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  67172. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  67173. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  67174. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  67175. return p;
  67176. });
  67177. return {values: values, xyMinMax: xyMinMax};
  67178. }
  67179. };
  67180. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  67181. if (__DEV__) {
  67182. assert$1(
  67183. coordSys.type === 'cartesian2d',
  67184. 'lineX/lineY brush is available only in cartesian2d.'
  67185. );
  67186. }
  67187. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  67188. var values = formatMinMax(map([0, 1], function (i) {
  67189. return to
  67190. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  67191. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  67192. }));
  67193. var xyMinMax = [];
  67194. xyMinMax[axisNameIndex] = values;
  67195. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  67196. return {values: values, xyMinMax: xyMinMax};
  67197. }
  67198. var diffProcessor = {
  67199. lineX: curry$5(axisDiffProcessor, 0),
  67200. lineY: curry$5(axisDiffProcessor, 1),
  67201. rect: function (values, refer, scales) {
  67202. return [
  67203. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  67204. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  67205. ];
  67206. },
  67207. polygon: function (values, refer, scales) {
  67208. return map(values, function (item, idx) {
  67209. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  67210. });
  67211. }
  67212. };
  67213. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  67214. return [
  67215. values[0] - scales[axisNameIndex] * refer[0],
  67216. values[1] - scales[axisNameIndex] * refer[1]
  67217. ];
  67218. }
  67219. // We have to process scale caused by dataZoom manually,
  67220. // although it might be not accurate.
  67221. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  67222. var sizeCurr = getSize(xyMinMaxCurr);
  67223. var sizeOrigin = getSize(xyMinMaxOrigin);
  67224. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  67225. isNaN(scales[0]) && (scales[0] = 1);
  67226. isNaN(scales[1]) && (scales[1] = 1);
  67227. return scales;
  67228. }
  67229. function getSize(xyMinMax) {
  67230. return xyMinMax
  67231. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  67232. : [NaN, NaN];
  67233. }
  67234. /*
  67235. * Licensed to the Apache Software Foundation (ASF) under one
  67236. * or more contributor license agreements. See the NOTICE file
  67237. * distributed with this work for additional information
  67238. * regarding copyright ownership. The ASF licenses this file
  67239. * to you under the Apache License, Version 2.0 (the
  67240. * "License"); you may not use this file except in compliance
  67241. * with the License. You may obtain a copy of the License at
  67242. *
  67243. * http://www.apache.org/licenses/LICENSE-2.0
  67244. *
  67245. * Unless required by applicable law or agreed to in writing,
  67246. * software distributed under the License is distributed on an
  67247. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67248. * KIND, either express or implied. See the License for the
  67249. * specific language governing permissions and limitations
  67250. * under the License.
  67251. */
  67252. var STATE_LIST = ['inBrush', 'outOfBrush'];
  67253. var DISPATCH_METHOD = '__ecBrushSelect';
  67254. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  67255. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  67256. /**
  67257. * Layout for visual, the priority higher than other layout, and before brush visual.
  67258. */
  67259. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  67260. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  67261. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  67262. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  67263. );
  67264. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  67265. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  67266. });
  67267. });
  67268. /**
  67269. * Register the visual encoding if this modules required.
  67270. */
  67271. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  67272. var brushSelected = [];
  67273. var throttleType;
  67274. var throttleDelay;
  67275. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  67276. var thisBrushSelected = {
  67277. brushId: brushModel.id,
  67278. brushIndex: brushIndex,
  67279. brushName: brushModel.name,
  67280. areas: clone(brushModel.areas),
  67281. selected: []
  67282. };
  67283. // Every brush component exists in event params, convenient
  67284. // for user to find by index.
  67285. brushSelected.push(thisBrushSelected);
  67286. var brushOption = brushModel.option;
  67287. var brushLink = brushOption.brushLink;
  67288. var linkedSeriesMap = [];
  67289. var selectedDataIndexForLink = [];
  67290. var rangeInfoBySeries = [];
  67291. var hasBrushExists = 0;
  67292. if (!brushIndex) { // Only the first throttle setting works.
  67293. throttleType = brushOption.throttleType;
  67294. throttleDelay = brushOption.throttleDelay;
  67295. }
  67296. // Add boundingRect and selectors to range.
  67297. var areas = map(brushModel.areas, function (area) {
  67298. return bindSelector(
  67299. defaults(
  67300. {boundingRect: boundingRectBuilders[area.brushType](area)},
  67301. area
  67302. )
  67303. );
  67304. });
  67305. var visualMappings = createVisualMappings(
  67306. brushModel.option, STATE_LIST, function (mappingOption) {
  67307. mappingOption.mappingMethod = 'fixed';
  67308. }
  67309. );
  67310. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  67311. linkedSeriesMap[seriesIndex] = 1;
  67312. });
  67313. function linkOthers(seriesIndex) {
  67314. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  67315. }
  67316. // If no supported brush or no brush on the series,
  67317. // all visuals should be in original state.
  67318. function brushed(rangeInfoList) {
  67319. return !!rangeInfoList.length;
  67320. }
  67321. /**
  67322. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  67323. *
  67324. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  67325. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  67326. * └!hasBrushExist┘ └nothing.
  67327. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  67328. * └!hasBrushExist┘ └nothing.
  67329. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  67330. * !brushed┘ └nothing.
  67331. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  67332. */
  67333. // Step A
  67334. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  67335. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  67336. seriesModel.subType === 'parallel'
  67337. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  67338. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  67339. });
  67340. function stepAParallel(seriesModel, seriesIndex) {
  67341. var coordSys = seriesModel.coordinateSystem;
  67342. hasBrushExists |= coordSys.hasAxisBrushed();
  67343. linkOthers(seriesIndex) && coordSys.eachActiveState(
  67344. seriesModel.getData(),
  67345. function (activeState, dataIndex) {
  67346. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  67347. }
  67348. );
  67349. }
  67350. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  67351. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  67352. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  67353. return;
  67354. }
  67355. each$1(areas, function (area) {
  67356. selectorsByBrushType[area.brushType]
  67357. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  67358. && rangeInfoList.push(area);
  67359. hasBrushExists |= brushed(rangeInfoList);
  67360. });
  67361. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  67362. var data = seriesModel.getData();
  67363. data.each(function (dataIndex) {
  67364. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  67365. selectedDataIndexForLink[dataIndex] = 1;
  67366. }
  67367. });
  67368. }
  67369. }
  67370. // Step B
  67371. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  67372. var seriesBrushSelected = {
  67373. seriesId: seriesModel.id,
  67374. seriesIndex: seriesIndex,
  67375. seriesName: seriesModel.name,
  67376. dataIndex: []
  67377. };
  67378. // Every series exists in event params, convenient
  67379. // for user to find series by seriesIndex.
  67380. thisBrushSelected.selected.push(seriesBrushSelected);
  67381. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  67382. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  67383. var data = seriesModel.getData();
  67384. var getValueState = linkOthers(seriesIndex)
  67385. ? function (dataIndex) {
  67386. return selectedDataIndexForLink[dataIndex]
  67387. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  67388. : 'outOfBrush';
  67389. }
  67390. : function (dataIndex) {
  67391. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  67392. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  67393. : 'outOfBrush';
  67394. };
  67395. // If no supported brush or no brush, all visuals are in original state.
  67396. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  67397. && applyVisual(
  67398. STATE_LIST, visualMappings, data, getValueState
  67399. );
  67400. });
  67401. });
  67402. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  67403. });
  67404. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  67405. // This event will not be triggered when `setOpion`, otherwise dead lock may
  67406. // triggered when do `setOption` in event listener, which we do not find
  67407. // satisfactory way to solve yet. Some considered resolutions:
  67408. // (a) Diff with prevoius selected data ant only trigger event when changed.
  67409. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  67410. // also detect value changes in selected data) might bring complexity or fragility.
  67411. // (b) Use spectial param like `silent` to suppress event triggering.
  67412. // But such kind of volatile param may be weird in `setOption`.
  67413. if (!payload) {
  67414. return;
  67415. }
  67416. var zr = api.getZr();
  67417. if (zr[DISPATCH_FLAG]) {
  67418. return;
  67419. }
  67420. if (!zr[DISPATCH_METHOD]) {
  67421. zr[DISPATCH_METHOD] = doDispatch;
  67422. }
  67423. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  67424. fn(api, brushSelected);
  67425. }
  67426. function doDispatch(api, brushSelected) {
  67427. if (!api.isDisposed()) {
  67428. var zr = api.getZr();
  67429. zr[DISPATCH_FLAG] = true;
  67430. api.dispatchAction({
  67431. type: 'brushSelect',
  67432. batch: brushSelected
  67433. });
  67434. zr[DISPATCH_FLAG] = false;
  67435. }
  67436. }
  67437. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  67438. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  67439. var area = rangeInfoList[i];
  67440. if (selectorsByBrushType[area.brushType](
  67441. dataIndex, data, area.selectors, area
  67442. )) {
  67443. return true;
  67444. }
  67445. }
  67446. }
  67447. function getSelectorsByBrushType(seriesModel) {
  67448. var brushSelector = seriesModel.brushSelector;
  67449. if (isString(brushSelector)) {
  67450. var sels = [];
  67451. each$1(selector, function (selectorsByElementType, brushType) {
  67452. sels[brushType] = function (dataIndex, data, selectors, area) {
  67453. var itemLayout = data.getItemLayout(dataIndex);
  67454. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  67455. };
  67456. });
  67457. return sels;
  67458. }
  67459. else if (isFunction$1(brushSelector)) {
  67460. var bSelector = {};
  67461. each$1(selector, function (sel, brushType) {
  67462. bSelector[brushType] = brushSelector;
  67463. });
  67464. return bSelector;
  67465. }
  67466. return brushSelector;
  67467. }
  67468. function brushModelNotControll(brushModel, seriesIndex) {
  67469. var seriesIndices = brushModel.option.seriesIndex;
  67470. return seriesIndices != null
  67471. && seriesIndices !== 'all'
  67472. && (
  67473. isArray(seriesIndices)
  67474. ? indexOf(seriesIndices, seriesIndex) < 0
  67475. : seriesIndex !== seriesIndices
  67476. );
  67477. }
  67478. function bindSelector(area) {
  67479. var selectors = area.selectors = {};
  67480. each$1(selector[area.brushType], function (selFn, elType) {
  67481. // Do not use function binding or curry for performance.
  67482. selectors[elType] = function (itemLayout) {
  67483. return selFn(itemLayout, selectors, area);
  67484. };
  67485. });
  67486. return area;
  67487. }
  67488. var boundingRectBuilders = {
  67489. lineX: noop,
  67490. lineY: noop,
  67491. rect: function (area) {
  67492. return getBoundingRectFromMinMax(area.range);
  67493. },
  67494. polygon: function (area) {
  67495. var minMax;
  67496. var range = area.range;
  67497. for (var i = 0, len = range.length; i < len; i++) {
  67498. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  67499. var rg = range[i];
  67500. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  67501. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  67502. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  67503. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  67504. }
  67505. return minMax && getBoundingRectFromMinMax(minMax);
  67506. }
  67507. };
  67508. function getBoundingRectFromMinMax(minMax) {
  67509. return new BoundingRect(
  67510. minMax[0][0],
  67511. minMax[1][0],
  67512. minMax[0][1] - minMax[0][0],
  67513. minMax[1][1] - minMax[1][0]
  67514. );
  67515. }
  67516. /*
  67517. * Licensed to the Apache Software Foundation (ASF) under one
  67518. * or more contributor license agreements. See the NOTICE file
  67519. * distributed with this work for additional information
  67520. * regarding copyright ownership. The ASF licenses this file
  67521. * to you under the Apache License, Version 2.0 (the
  67522. * "License"); you may not use this file except in compliance
  67523. * with the License. You may obtain a copy of the License at
  67524. *
  67525. * http://www.apache.org/licenses/LICENSE-2.0
  67526. *
  67527. * Unless required by applicable law or agreed to in writing,
  67528. * software distributed under the License is distributed on an
  67529. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67530. * KIND, either express or implied. See the License for the
  67531. * specific language governing permissions and limitations
  67532. * under the License.
  67533. */
  67534. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  67535. var BrushModel = extendComponentModel({
  67536. type: 'brush',
  67537. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  67538. /**
  67539. * @protected
  67540. */
  67541. defaultOption: {
  67542. // inBrush: null,
  67543. // outOfBrush: null,
  67544. toolbox: null, // Default value see preprocessor.
  67545. brushLink: null, // Series indices array, broadcast using dataIndex.
  67546. // or 'all', which means all series. 'none' or null means no series.
  67547. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  67548. geoIndex: null, //
  67549. xAxisIndex: null,
  67550. yAxisIndex: null,
  67551. brushType: 'rect', // Default brushType, see BrushController.
  67552. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  67553. transformable: true, // Default transformable.
  67554. brushStyle: { // Default brushStyle
  67555. borderWidth: 1,
  67556. color: 'rgba(120,140,180,0.3)',
  67557. borderColor: 'rgba(120,140,180,0.8)'
  67558. },
  67559. throttleType: 'fixRate', // Throttle in brushSelected event. 'fixRate' or 'debounce'.
  67560. // If null, no throttle. Valid only in the first brush component
  67561. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  67562. // FIXME
  67563. // 试验效果
  67564. removeOnClick: true,
  67565. z: 10000
  67566. },
  67567. /**
  67568. * @readOnly
  67569. * @type {Array.<Object>}
  67570. */
  67571. areas: [],
  67572. /**
  67573. * Current activated brush type.
  67574. * If null, brush is inactived.
  67575. * see module:echarts/component/helper/BrushController
  67576. * @readOnly
  67577. * @type {string}
  67578. */
  67579. brushType: null,
  67580. /**
  67581. * Current brush opt.
  67582. * see module:echarts/component/helper/BrushController
  67583. * @readOnly
  67584. * @type {Object}
  67585. */
  67586. brushOption: {},
  67587. /**
  67588. * @readOnly
  67589. * @type {Array.<Object>}
  67590. */
  67591. coordInfoList: [],
  67592. optionUpdated: function (newOption, isInit) {
  67593. var thisOption = this.option;
  67594. !isInit && replaceVisualOption(
  67595. thisOption, newOption, ['inBrush', 'outOfBrush']
  67596. );
  67597. var inBrush = thisOption.inBrush = thisOption.inBrush || {};
  67598. // Always give default visual, consider setOption at the second time.
  67599. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  67600. if (!inBrush.hasOwnProperty('liftZ')) {
  67601. // Bigger than the highlight z lift, otherwise it will
  67602. // be effected by the highlight z when brush.
  67603. inBrush.liftZ = 5;
  67604. }
  67605. },
  67606. /**
  67607. * If ranges is null/undefined, range state remain.
  67608. *
  67609. * @param {Array.<Object>} [ranges]
  67610. */
  67611. setAreas: function (areas) {
  67612. if (__DEV__) {
  67613. assert$1(isArray(areas));
  67614. each$1(areas, function (area) {
  67615. assert$1(area.brushType, 'Illegal areas');
  67616. });
  67617. }
  67618. // If ranges is null/undefined, range state remain.
  67619. // This helps user to dispatchAction({type: 'brush'}) with no areas
  67620. // set but just want to get the current brush select info from a `brush` event.
  67621. if (!areas) {
  67622. return;
  67623. }
  67624. this.areas = map(areas, function (area) {
  67625. return generateBrushOption(this.option, area);
  67626. }, this);
  67627. },
  67628. /**
  67629. * see module:echarts/component/helper/BrushController
  67630. * @param {Object} brushOption
  67631. */
  67632. setBrushOption: function (brushOption) {
  67633. this.brushOption = generateBrushOption(this.option, brushOption);
  67634. this.brushType = this.brushOption.brushType;
  67635. }
  67636. });
  67637. function generateBrushOption(option, brushOption) {
  67638. return merge(
  67639. {
  67640. brushType: option.brushType,
  67641. brushMode: option.brushMode,
  67642. transformable: option.transformable,
  67643. brushStyle: new Model(option.brushStyle).getItemStyle(),
  67644. removeOnClick: option.removeOnClick,
  67645. z: option.z
  67646. },
  67647. brushOption,
  67648. true
  67649. );
  67650. }
  67651. /*
  67652. * Licensed to the Apache Software Foundation (ASF) under one
  67653. * or more contributor license agreements. See the NOTICE file
  67654. * distributed with this work for additional information
  67655. * regarding copyright ownership. The ASF licenses this file
  67656. * to you under the Apache License, Version 2.0 (the
  67657. * "License"); you may not use this file except in compliance
  67658. * with the License. You may obtain a copy of the License at
  67659. *
  67660. * http://www.apache.org/licenses/LICENSE-2.0
  67661. *
  67662. * Unless required by applicable law or agreed to in writing,
  67663. * software distributed under the License is distributed on an
  67664. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67665. * KIND, either express or implied. See the License for the
  67666. * specific language governing permissions and limitations
  67667. * under the License.
  67668. */
  67669. extendComponentView({
  67670. type: 'brush',
  67671. init: function (ecModel, api) {
  67672. /**
  67673. * @readOnly
  67674. * @type {module:echarts/model/Global}
  67675. */
  67676. this.ecModel = ecModel;
  67677. /**
  67678. * @readOnly
  67679. * @type {module:echarts/ExtensionAPI}
  67680. */
  67681. this.api = api;
  67682. /**
  67683. * @readOnly
  67684. * @type {module:echarts/component/brush/BrushModel}
  67685. */
  67686. this.model;
  67687. /**
  67688. * @private
  67689. * @type {module:echarts/component/helper/BrushController}
  67690. */
  67691. (this._brushController = new BrushController(api.getZr()))
  67692. .on('brush', bind(this._onBrush, this))
  67693. .mount();
  67694. },
  67695. /**
  67696. * @override
  67697. */
  67698. render: function (brushModel) {
  67699. this.model = brushModel;
  67700. return updateController.apply(this, arguments);
  67701. },
  67702. /**
  67703. * @override
  67704. */
  67705. updateTransform: updateController,
  67706. /**
  67707. * @override
  67708. */
  67709. updateView: updateController,
  67710. // /**
  67711. // * @override
  67712. // */
  67713. // updateLayout: updateController,
  67714. // /**
  67715. // * @override
  67716. // */
  67717. // updateVisual: updateController,
  67718. /**
  67719. * @override
  67720. */
  67721. dispose: function () {
  67722. this._brushController.dispose();
  67723. },
  67724. /**
  67725. * @private
  67726. */
  67727. _onBrush: function (areas, opt) {
  67728. var modelId = this.model.id;
  67729. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  67730. // Action is not dispatched on drag end, because the drag end
  67731. // emits the same params with the last drag move event, and
  67732. // may have some delay when using touch pad, which makes
  67733. // animation not smooth (when using debounce).
  67734. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  67735. type: 'brush',
  67736. brushId: modelId,
  67737. areas: clone(areas),
  67738. $from: modelId
  67739. });
  67740. }
  67741. });
  67742. function updateController(brushModel, ecModel, api, payload) {
  67743. // Do not update controller when drawing.
  67744. (!payload || payload.$from !== brushModel.id) && this._brushController
  67745. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  67746. .enableBrush(brushModel.brushOption)
  67747. .updateCovers(brushModel.areas.slice());
  67748. }
  67749. /*
  67750. * Licensed to the Apache Software Foundation (ASF) under one
  67751. * or more contributor license agreements. See the NOTICE file
  67752. * distributed with this work for additional information
  67753. * regarding copyright ownership. The ASF licenses this file
  67754. * to you under the Apache License, Version 2.0 (the
  67755. * "License"); you may not use this file except in compliance
  67756. * with the License. You may obtain a copy of the License at
  67757. *
  67758. * http://www.apache.org/licenses/LICENSE-2.0
  67759. *
  67760. * Unless required by applicable law or agreed to in writing,
  67761. * software distributed under the License is distributed on an
  67762. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67763. * KIND, either express or implied. See the License for the
  67764. * specific language governing permissions and limitations
  67765. * under the License.
  67766. */
  67767. /**
  67768. * payload: {
  67769. * brushIndex: number, or,
  67770. * brushId: string, or,
  67771. * brushName: string,
  67772. * globalRanges: Array
  67773. * }
  67774. */
  67775. registerAction(
  67776. {type: 'brush', event: 'brush' /*, update: 'updateView' */},
  67777. function (payload, ecModel) {
  67778. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  67779. brushModel.setAreas(payload.areas);
  67780. });
  67781. }
  67782. );
  67783. /**
  67784. * payload: {
  67785. * brushComponents: [
  67786. * {
  67787. * brushId,
  67788. * brushIndex,
  67789. * brushName,
  67790. * series: [
  67791. * {
  67792. * seriesId,
  67793. * seriesIndex,
  67794. * seriesName,
  67795. * rawIndices: [21, 34, ...]
  67796. * },
  67797. * ...
  67798. * ]
  67799. * },
  67800. * ...
  67801. * ]
  67802. * }
  67803. */
  67804. registerAction(
  67805. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  67806. function () {}
  67807. );
  67808. /*
  67809. * Licensed to the Apache Software Foundation (ASF) under one
  67810. * or more contributor license agreements. See the NOTICE file
  67811. * distributed with this work for additional information
  67812. * regarding copyright ownership. The ASF licenses this file
  67813. * to you under the Apache License, Version 2.0 (the
  67814. * "License"); you may not use this file except in compliance
  67815. * with the License. You may obtain a copy of the License at
  67816. *
  67817. * http://www.apache.org/licenses/LICENSE-2.0
  67818. *
  67819. * Unless required by applicable law or agreed to in writing,
  67820. * software distributed under the License is distributed on an
  67821. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67822. * KIND, either express or implied. See the License for the
  67823. * specific language governing permissions and limitations
  67824. * under the License.
  67825. */
  67826. var features = {};
  67827. function register$1(name, ctor) {
  67828. features[name] = ctor;
  67829. }
  67830. function get$1(name) {
  67831. return features[name];
  67832. }
  67833. /*
  67834. * Licensed to the Apache Software Foundation (ASF) under one
  67835. * or more contributor license agreements. See the NOTICE file
  67836. * distributed with this work for additional information
  67837. * regarding copyright ownership. The ASF licenses this file
  67838. * to you under the Apache License, Version 2.0 (the
  67839. * "License"); you may not use this file except in compliance
  67840. * with the License. You may obtain a copy of the License at
  67841. *
  67842. * http://www.apache.org/licenses/LICENSE-2.0
  67843. *
  67844. * Unless required by applicable law or agreed to in writing,
  67845. * software distributed under the License is distributed on an
  67846. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67847. * KIND, either express or implied. See the License for the
  67848. * specific language governing permissions and limitations
  67849. * under the License.
  67850. */
  67851. var brushLang = lang.toolbox.brush;
  67852. function Brush(model, ecModel, api) {
  67853. this.model = model;
  67854. this.ecModel = ecModel;
  67855. this.api = api;
  67856. /**
  67857. * @private
  67858. * @type {string}
  67859. */
  67860. this._brushType;
  67861. /**
  67862. * @private
  67863. * @type {string}
  67864. */
  67865. this._brushMode;
  67866. }
  67867. Brush.defaultOption = {
  67868. show: true,
  67869. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  67870. icon: {
  67871. /* eslint-disable */
  67872. 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
  67873. 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
  67874. 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
  67875. 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
  67876. 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
  67877. 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
  67878. /* eslint-enable */
  67879. },
  67880. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  67881. title: clone(brushLang.title)
  67882. };
  67883. var proto$3 = Brush.prototype;
  67884. // proto.updateLayout = function (featureModel, ecModel, api) {
  67885. /* eslint-disable */
  67886. proto$3.render =
  67887. /* eslint-enable */
  67888. proto$3.updateView = function (featureModel, ecModel, api) {
  67889. var brushType;
  67890. var brushMode;
  67891. var isBrushed;
  67892. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  67893. brushType = brushModel.brushType;
  67894. brushMode = brushModel.brushOption.brushMode || 'single';
  67895. isBrushed |= brushModel.areas.length;
  67896. });
  67897. this._brushType = brushType;
  67898. this._brushMode = brushMode;
  67899. each$1(featureModel.get('type', true), function (type) {
  67900. featureModel.setIconStatus(
  67901. type,
  67902. (
  67903. type === 'keep'
  67904. ? brushMode === 'multiple'
  67905. : type === 'clear'
  67906. ? isBrushed
  67907. : type === brushType
  67908. ) ? 'emphasis' : 'normal'
  67909. );
  67910. });
  67911. };
  67912. proto$3.getIcons = function () {
  67913. var model = this.model;
  67914. var availableIcons = model.get('icon', true);
  67915. var icons = {};
  67916. each$1(model.get('type', true), function (type) {
  67917. if (availableIcons[type]) {
  67918. icons[type] = availableIcons[type];
  67919. }
  67920. });
  67921. return icons;
  67922. };
  67923. proto$3.onclick = function (ecModel, api, type) {
  67924. var brushType = this._brushType;
  67925. var brushMode = this._brushMode;
  67926. if (type === 'clear') {
  67927. // Trigger parallel action firstly
  67928. api.dispatchAction({
  67929. type: 'axisAreaSelect',
  67930. intervals: []
  67931. });
  67932. api.dispatchAction({
  67933. type: 'brush',
  67934. command: 'clear',
  67935. // Clear all areas of all brush components.
  67936. areas: []
  67937. });
  67938. }
  67939. else {
  67940. api.dispatchAction({
  67941. type: 'takeGlobalCursor',
  67942. key: 'brush',
  67943. brushOption: {
  67944. brushType: type === 'keep'
  67945. ? brushType
  67946. : (brushType === type ? false : type),
  67947. brushMode: type === 'keep'
  67948. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  67949. : brushMode
  67950. }
  67951. });
  67952. }
  67953. };
  67954. register$1('brush', Brush);
  67955. /*
  67956. * Licensed to the Apache Software Foundation (ASF) under one
  67957. * or more contributor license agreements. See the NOTICE file
  67958. * distributed with this work for additional information
  67959. * regarding copyright ownership. The ASF licenses this file
  67960. * to you under the Apache License, Version 2.0 (the
  67961. * "License"); you may not use this file except in compliance
  67962. * with the License. You may obtain a copy of the License at
  67963. *
  67964. * http://www.apache.org/licenses/LICENSE-2.0
  67965. *
  67966. * Unless required by applicable law or agreed to in writing,
  67967. * software distributed under the License is distributed on an
  67968. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67969. * KIND, either express or implied. See the License for the
  67970. * specific language governing permissions and limitations
  67971. * under the License.
  67972. */
  67973. /**
  67974. * Brush component entry
  67975. */
  67976. registerPreprocessor(preprocessor$1);
  67977. /*
  67978. * Licensed to the Apache Software Foundation (ASF) under one
  67979. * or more contributor license agreements. See the NOTICE file
  67980. * distributed with this work for additional information
  67981. * regarding copyright ownership. The ASF licenses this file
  67982. * to you under the Apache License, Version 2.0 (the
  67983. * "License"); you may not use this file except in compliance
  67984. * with the License. You may obtain a copy of the License at
  67985. *
  67986. * http://www.apache.org/licenses/LICENSE-2.0
  67987. *
  67988. * Unless required by applicable law or agreed to in writing,
  67989. * software distributed under the License is distributed on an
  67990. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67991. * KIND, either express or implied. See the License for the
  67992. * specific language governing permissions and limitations
  67993. * under the License.
  67994. */
  67995. // (24*60*60*1000)
  67996. var PROXIMATE_ONE_DAY = 86400000;
  67997. /**
  67998. * Calendar
  67999. *
  68000. * @constructor
  68001. *
  68002. * @param {Object} calendarModel calendarModel
  68003. * @param {Object} ecModel ecModel
  68004. * @param {Object} api api
  68005. */
  68006. function Calendar(calendarModel, ecModel, api) {
  68007. this._model = calendarModel;
  68008. }
  68009. Calendar.prototype = {
  68010. constructor: Calendar,
  68011. type: 'calendar',
  68012. dimensions: ['time', 'value'],
  68013. // Required in createListFromData
  68014. getDimensionsInfo: function () {
  68015. return [{name: 'time', type: 'time'}, 'value'];
  68016. },
  68017. getRangeInfo: function () {
  68018. return this._rangeInfo;
  68019. },
  68020. getModel: function () {
  68021. return this._model;
  68022. },
  68023. getRect: function () {
  68024. return this._rect;
  68025. },
  68026. getCellWidth: function () {
  68027. return this._sw;
  68028. },
  68029. getCellHeight: function () {
  68030. return this._sh;
  68031. },
  68032. getOrient: function () {
  68033. return this._orient;
  68034. },
  68035. /**
  68036. * getFirstDayOfWeek
  68037. *
  68038. * @example
  68039. * 0 : start at Sunday
  68040. * 1 : start at Monday
  68041. *
  68042. * @return {number}
  68043. */
  68044. getFirstDayOfWeek: function () {
  68045. return this._firstDayOfWeek;
  68046. },
  68047. /**
  68048. * get date info
  68049. *
  68050. * @param {string|number} date date
  68051. * @return {Object}
  68052. * {
  68053. * y: string, local full year, eg., '1940',
  68054. * m: string, local month, from '01' ot '12',
  68055. * d: string, local date, from '01' to '31' (if exists),
  68056. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  68057. * time: timestamp,
  68058. * formatedDate: string, yyyy-MM-dd,
  68059. * date: original date object.
  68060. * }
  68061. */
  68062. getDateInfo: function (date) {
  68063. date = parseDate(date);
  68064. var y = date.getFullYear();
  68065. var m = date.getMonth() + 1;
  68066. m = m < 10 ? '0' + m : m;
  68067. var d = date.getDate();
  68068. d = d < 10 ? '0' + d : d;
  68069. var day = date.getDay();
  68070. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  68071. return {
  68072. y: y,
  68073. m: m,
  68074. d: d,
  68075. day: day,
  68076. time: date.getTime(),
  68077. formatedDate: y + '-' + m + '-' + d,
  68078. date: date
  68079. };
  68080. },
  68081. getNextNDay: function (date, n) {
  68082. n = n || 0;
  68083. if (n === 0) {
  68084. return this.getDateInfo(date);
  68085. }
  68086. date = new Date(this.getDateInfo(date).time);
  68087. date.setDate(date.getDate() + n);
  68088. return this.getDateInfo(date);
  68089. },
  68090. update: function (ecModel, api) {
  68091. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  68092. this._orient = this._model.get('orient');
  68093. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  68094. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  68095. var weeks = this._rangeInfo.weeks || 1;
  68096. var whNames = ['width', 'height'];
  68097. var cellSize = this._model.get('cellSize').slice();
  68098. var layoutParams = this._model.getBoxLayoutParams();
  68099. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  68100. each$1([0, 1], function (idx) {
  68101. if (cellSizeSpecified(cellSize, idx)) {
  68102. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  68103. }
  68104. });
  68105. var whGlobal = {
  68106. width: api.getWidth(),
  68107. height: api.getHeight()
  68108. };
  68109. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  68110. each$1([0, 1], function (idx) {
  68111. if (!cellSizeSpecified(cellSize, idx)) {
  68112. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  68113. }
  68114. });
  68115. function cellSizeSpecified(cellSize, idx) {
  68116. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  68117. }
  68118. this._sw = cellSize[0];
  68119. this._sh = cellSize[1];
  68120. },
  68121. /**
  68122. * Convert a time data(time, value) item to (x, y) point.
  68123. *
  68124. * @override
  68125. * @param {Array|number} data data
  68126. * @param {boolean} [clamp=true] out of range
  68127. * @return {Array} point
  68128. */
  68129. dataToPoint: function (data, clamp) {
  68130. isArray(data) && (data = data[0]);
  68131. clamp == null && (clamp = true);
  68132. var dayInfo = this.getDateInfo(data);
  68133. var range = this._rangeInfo;
  68134. var date = dayInfo.formatedDate;
  68135. // if not in range return [NaN, NaN]
  68136. if (clamp && !(
  68137. dayInfo.time >= range.start.time
  68138. && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY
  68139. )) {
  68140. return [NaN, NaN];
  68141. }
  68142. var week = dayInfo.day;
  68143. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  68144. if (this._orient === 'vertical') {
  68145. return [
  68146. this._rect.x + week * this._sw + this._sw / 2,
  68147. this._rect.y + nthWeek * this._sh + this._sh / 2
  68148. ];
  68149. }
  68150. return [
  68151. this._rect.x + nthWeek * this._sw + this._sw / 2,
  68152. this._rect.y + week * this._sh + this._sh / 2
  68153. ];
  68154. },
  68155. /**
  68156. * Convert a (x, y) point to time data
  68157. *
  68158. * @override
  68159. * @param {string} point point
  68160. * @return {string} data
  68161. */
  68162. pointToData: function (point) {
  68163. var date = this.pointToDate(point);
  68164. return date && date.time;
  68165. },
  68166. /**
  68167. * Convert a time date item to (x, y) four point.
  68168. *
  68169. * @param {Array} data date[0] is date
  68170. * @param {boolean} [clamp=true] out of range
  68171. * @return {Object} point
  68172. */
  68173. dataToRect: function (data, clamp) {
  68174. var point = this.dataToPoint(data, clamp);
  68175. return {
  68176. contentShape: {
  68177. x: point[0] - (this._sw - this._lineWidth) / 2,
  68178. y: point[1] - (this._sh - this._lineWidth) / 2,
  68179. width: this._sw - this._lineWidth,
  68180. height: this._sh - this._lineWidth
  68181. },
  68182. center: point,
  68183. tl: [
  68184. point[0] - this._sw / 2,
  68185. point[1] - this._sh / 2
  68186. ],
  68187. tr: [
  68188. point[0] + this._sw / 2,
  68189. point[1] - this._sh / 2
  68190. ],
  68191. br: [
  68192. point[0] + this._sw / 2,
  68193. point[1] + this._sh / 2
  68194. ],
  68195. bl: [
  68196. point[0] - this._sw / 2,
  68197. point[1] + this._sh / 2
  68198. ]
  68199. };
  68200. },
  68201. /**
  68202. * Convert a (x, y) point to time date
  68203. *
  68204. * @param {Array} point point
  68205. * @return {Object} date
  68206. */
  68207. pointToDate: function (point) {
  68208. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  68209. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  68210. var range = this._rangeInfo.range;
  68211. if (this._orient === 'vertical') {
  68212. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  68213. }
  68214. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  68215. },
  68216. /**
  68217. * @inheritDoc
  68218. */
  68219. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  68220. /**
  68221. * @inheritDoc
  68222. */
  68223. convertFromPixel: curry(doConvert$2, 'pointToData'),
  68224. /**
  68225. * initRange
  68226. *
  68227. * @private
  68228. * @return {Array} [start, end]
  68229. */
  68230. _initRangeOption: function () {
  68231. var range = this._model.get('range');
  68232. var rg = range;
  68233. if (isArray(rg) && rg.length === 1) {
  68234. rg = rg[0];
  68235. }
  68236. if (/^\d{4}$/.test(rg)) {
  68237. range = [rg + '-01-01', rg + '-12-31'];
  68238. }
  68239. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  68240. var start = this.getDateInfo(rg);
  68241. var firstDay = start.date;
  68242. firstDay.setMonth(firstDay.getMonth() + 1);
  68243. var end = this.getNextNDay(firstDay, -1);
  68244. range = [start.formatedDate, end.formatedDate];
  68245. }
  68246. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  68247. range = [rg, rg];
  68248. }
  68249. var tmp = this._getRangeInfo(range);
  68250. if (tmp.start.time > tmp.end.time) {
  68251. range.reverse();
  68252. }
  68253. return range;
  68254. },
  68255. /**
  68256. * range info
  68257. *
  68258. * @private
  68259. * @param {Array} range range ['2017-01-01', '2017-07-08']
  68260. * If range[0] > range[1], they will not be reversed.
  68261. * @return {Object} obj
  68262. */
  68263. _getRangeInfo: function (range) {
  68264. range = [
  68265. this.getDateInfo(range[0]),
  68266. this.getDateInfo(range[1])
  68267. ];
  68268. var reversed;
  68269. if (range[0].time > range[1].time) {
  68270. reversed = true;
  68271. range.reverse();
  68272. }
  68273. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  68274. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  68275. // Consider case:
  68276. // Firstly set system timezone as "Time Zone: America/Toronto",
  68277. // ```
  68278. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  68279. // var second = new Date(1478412000000);
  68280. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  68281. // ```
  68282. // will get wrong result because of DST. So we should fix it.
  68283. var date = new Date(range[0].time);
  68284. var startDateNum = date.getDate();
  68285. var endDateNum = range[1].date.getDate();
  68286. date.setDate(startDateNum + allDay - 1);
  68287. // The bias can not over a month, so just compare date.
  68288. if (date.getDate() !== endDateNum) {
  68289. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  68290. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  68291. allDay -= sign;
  68292. date.setDate(startDateNum + allDay - 1);
  68293. }
  68294. }
  68295. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  68296. var nthWeek = reversed ? -weeks + 1 : weeks - 1;
  68297. reversed && range.reverse();
  68298. return {
  68299. range: [range[0].formatedDate, range[1].formatedDate],
  68300. start: range[0],
  68301. end: range[1],
  68302. allDay: allDay,
  68303. weeks: weeks,
  68304. // From 0.
  68305. nthWeek: nthWeek,
  68306. fweek: range[0].day,
  68307. lweek: range[1].day
  68308. };
  68309. },
  68310. /**
  68311. * get date by nthWeeks and week day in range
  68312. *
  68313. * @private
  68314. * @param {number} nthWeek the week
  68315. * @param {number} day the week day
  68316. * @param {Array} range [d1, d2]
  68317. * @return {Object}
  68318. */
  68319. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  68320. var rangeInfo = this._getRangeInfo(range);
  68321. if (nthWeek > rangeInfo.weeks
  68322. || (nthWeek === 0 && day < rangeInfo.fweek)
  68323. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  68324. ) {
  68325. return false;
  68326. }
  68327. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  68328. var date = new Date(rangeInfo.start.time);
  68329. date.setDate(rangeInfo.start.d + nthDay);
  68330. return this.getDateInfo(date);
  68331. }
  68332. };
  68333. Calendar.dimensions = Calendar.prototype.dimensions;
  68334. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  68335. Calendar.create = function (ecModel, api) {
  68336. var calendarList = [];
  68337. ecModel.eachComponent('calendar', function (calendarModel) {
  68338. var calendar = new Calendar(calendarModel, ecModel, api);
  68339. calendarList.push(calendar);
  68340. calendarModel.coordinateSystem = calendar;
  68341. });
  68342. ecModel.eachSeries(function (calendarSeries) {
  68343. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  68344. // Inject coordinate system
  68345. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  68346. }
  68347. });
  68348. return calendarList;
  68349. };
  68350. function doConvert$2(methodName, ecModel, finder, value) {
  68351. var calendarModel = finder.calendarModel;
  68352. var seriesModel = finder.seriesModel;
  68353. var coordSys = calendarModel
  68354. ? calendarModel.coordinateSystem
  68355. : seriesModel
  68356. ? seriesModel.coordinateSystem
  68357. : null;
  68358. return coordSys === this ? coordSys[methodName](value) : null;
  68359. }
  68360. CoordinateSystemManager.register('calendar', Calendar);
  68361. /*
  68362. * Licensed to the Apache Software Foundation (ASF) under one
  68363. * or more contributor license agreements. See the NOTICE file
  68364. * distributed with this work for additional information
  68365. * regarding copyright ownership. The ASF licenses this file
  68366. * to you under the Apache License, Version 2.0 (the
  68367. * "License"); you may not use this file except in compliance
  68368. * with the License. You may obtain a copy of the License at
  68369. *
  68370. * http://www.apache.org/licenses/LICENSE-2.0
  68371. *
  68372. * Unless required by applicable law or agreed to in writing,
  68373. * software distributed under the License is distributed on an
  68374. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68375. * KIND, either express or implied. See the License for the
  68376. * specific language governing permissions and limitations
  68377. * under the License.
  68378. */
  68379. var CalendarModel = ComponentModel.extend({
  68380. type: 'calendar',
  68381. /**
  68382. * @type {module:echarts/coord/calendar/Calendar}
  68383. */
  68384. coordinateSystem: null,
  68385. defaultOption: {
  68386. zlevel: 0,
  68387. z: 2,
  68388. left: 80,
  68389. top: 60,
  68390. cellSize: 20,
  68391. // horizontal vertical
  68392. orient: 'horizontal',
  68393. // month separate line style
  68394. splitLine: {
  68395. show: true,
  68396. lineStyle: {
  68397. color: '#000',
  68398. width: 1,
  68399. type: 'solid'
  68400. }
  68401. },
  68402. // rect style temporarily unused emphasis
  68403. itemStyle: {
  68404. color: '#fff',
  68405. borderWidth: 1,
  68406. borderColor: '#ccc'
  68407. },
  68408. // week text style
  68409. dayLabel: {
  68410. show: true,
  68411. // a week first day
  68412. firstDay: 0,
  68413. // start end
  68414. position: 'start',
  68415. margin: '50%', // 50% of cellSize
  68416. nameMap: 'en',
  68417. color: '#000'
  68418. },
  68419. // month text style
  68420. monthLabel: {
  68421. show: true,
  68422. // start end
  68423. position: 'start',
  68424. margin: 5,
  68425. // center or left
  68426. align: 'center',
  68427. // cn en []
  68428. nameMap: 'en',
  68429. formatter: null,
  68430. color: '#000'
  68431. },
  68432. // year text style
  68433. yearLabel: {
  68434. show: true,
  68435. // top bottom left right
  68436. position: null,
  68437. margin: 30,
  68438. formatter: null,
  68439. color: '#ccc',
  68440. fontFamily: 'sans-serif',
  68441. fontWeight: 'bolder',
  68442. fontSize: 20
  68443. }
  68444. },
  68445. /**
  68446. * @override
  68447. */
  68448. init: function (option, parentModel, ecModel, extraOpt) {
  68449. var inputPositionParams = getLayoutParams(option);
  68450. CalendarModel.superApply(this, 'init', arguments);
  68451. mergeAndNormalizeLayoutParams$1(option, inputPositionParams);
  68452. },
  68453. /**
  68454. * @override
  68455. */
  68456. mergeOption: function (option, extraOpt) {
  68457. CalendarModel.superApply(this, 'mergeOption', arguments);
  68458. mergeAndNormalizeLayoutParams$1(this.option, option);
  68459. }
  68460. });
  68461. function mergeAndNormalizeLayoutParams$1(target, raw) {
  68462. // Normalize cellSize
  68463. var cellSize = target.cellSize;
  68464. if (!isArray(cellSize)) {
  68465. cellSize = target.cellSize = [cellSize, cellSize];
  68466. }
  68467. else if (cellSize.length === 1) {
  68468. cellSize[1] = cellSize[0];
  68469. }
  68470. var ignoreSize = map([0, 1], function (hvIdx) {
  68471. // If user have set `width` or both `left` and `right`, cellSize
  68472. // will be automatically set to 'auto', otherwise the default
  68473. // setting of cellSize will make `width` setting not work.
  68474. if (sizeCalculable(raw, hvIdx)) {
  68475. cellSize[hvIdx] = 'auto';
  68476. }
  68477. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  68478. });
  68479. mergeLayoutParam(target, raw, {
  68480. type: 'box', ignoreSize: ignoreSize
  68481. });
  68482. }
  68483. /*
  68484. * Licensed to the Apache Software Foundation (ASF) under one
  68485. * or more contributor license agreements. See the NOTICE file
  68486. * distributed with this work for additional information
  68487. * regarding copyright ownership. The ASF licenses this file
  68488. * to you under the Apache License, Version 2.0 (the
  68489. * "License"); you may not use this file except in compliance
  68490. * with the License. You may obtain a copy of the License at
  68491. *
  68492. * http://www.apache.org/licenses/LICENSE-2.0
  68493. *
  68494. * Unless required by applicable law or agreed to in writing,
  68495. * software distributed under the License is distributed on an
  68496. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68497. * KIND, either express or implied. See the License for the
  68498. * specific language governing permissions and limitations
  68499. * under the License.
  68500. */
  68501. var MONTH_TEXT = {
  68502. EN: [
  68503. 'Jan', 'Feb', 'Mar',
  68504. 'Apr', 'May', 'Jun',
  68505. 'Jul', 'Aug', 'Sep',
  68506. 'Oct', 'Nov', 'Dec'
  68507. ],
  68508. CN: [
  68509. '一月', '二月', '三月',
  68510. '四月', '五月', '六月',
  68511. '七月', '八月', '九月',
  68512. '十月', '十一月', '十二月'
  68513. ]
  68514. };
  68515. var WEEK_TEXT = {
  68516. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  68517. CN: ['日', '一', '二', '三', '四', '五', '六']
  68518. };
  68519. extendComponentView({
  68520. type: 'calendar',
  68521. /**
  68522. * top/left line points
  68523. * @private
  68524. */
  68525. _tlpoints: null,
  68526. /**
  68527. * bottom/right line points
  68528. * @private
  68529. */
  68530. _blpoints: null,
  68531. /**
  68532. * first day of month
  68533. * @private
  68534. */
  68535. _firstDayOfMonth: null,
  68536. /**
  68537. * first day point of month
  68538. * @private
  68539. */
  68540. _firstDayPoints: null,
  68541. render: function (calendarModel, ecModel, api) {
  68542. var group = this.group;
  68543. group.removeAll();
  68544. var coordSys = calendarModel.coordinateSystem;
  68545. // range info
  68546. var rangeData = coordSys.getRangeInfo();
  68547. var orient = coordSys.getOrient();
  68548. this._renderDayRect(calendarModel, rangeData, group);
  68549. // _renderLines must be called prior to following function
  68550. this._renderLines(calendarModel, rangeData, orient, group);
  68551. this._renderYearText(calendarModel, rangeData, orient, group);
  68552. this._renderMonthText(calendarModel, orient, group);
  68553. this._renderWeekText(calendarModel, rangeData, orient, group);
  68554. },
  68555. // render day rect
  68556. _renderDayRect: function (calendarModel, rangeData, group) {
  68557. var coordSys = calendarModel.coordinateSystem;
  68558. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  68559. var sw = coordSys.getCellWidth();
  68560. var sh = coordSys.getCellHeight();
  68561. for (var i = rangeData.start.time;
  68562. i <= rangeData.end.time;
  68563. i = coordSys.getNextNDay(i, 1).time
  68564. ) {
  68565. var point = coordSys.dataToRect([i], false).tl;
  68566. // every rect
  68567. var rect = new Rect({
  68568. shape: {
  68569. x: point[0],
  68570. y: point[1],
  68571. width: sw,
  68572. height: sh
  68573. },
  68574. cursor: 'default',
  68575. style: itemRectStyleModel
  68576. });
  68577. group.add(rect);
  68578. }
  68579. },
  68580. // render separate line
  68581. _renderLines: function (calendarModel, rangeData, orient, group) {
  68582. var self = this;
  68583. var coordSys = calendarModel.coordinateSystem;
  68584. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  68585. var show = calendarModel.get('splitLine.show');
  68586. var lineWidth = lineStyleModel.lineWidth;
  68587. this._tlpoints = [];
  68588. this._blpoints = [];
  68589. this._firstDayOfMonth = [];
  68590. this._firstDayPoints = [];
  68591. var firstDay = rangeData.start;
  68592. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  68593. addPoints(firstDay.formatedDate);
  68594. if (i === 0) {
  68595. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  68596. }
  68597. var date = firstDay.date;
  68598. date.setMonth(date.getMonth() + 1);
  68599. firstDay = coordSys.getDateInfo(date);
  68600. }
  68601. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  68602. function addPoints(date) {
  68603. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  68604. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  68605. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  68606. self._tlpoints.push(points[0]);
  68607. self._blpoints.push(points[points.length - 1]);
  68608. show && self._drawSplitline(points, lineStyleModel, group);
  68609. }
  68610. // render top/left line
  68611. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  68612. // render bottom/right line
  68613. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  68614. },
  68615. // get points at both ends
  68616. _getEdgesPoints: function (points, lineWidth, orient) {
  68617. var rs = [points[0].slice(), points[points.length - 1].slice()];
  68618. var idx = orient === 'horizontal' ? 0 : 1;
  68619. // both ends of the line are extend half lineWidth
  68620. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  68621. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  68622. return rs;
  68623. },
  68624. // render split line
  68625. _drawSplitline: function (points, lineStyleModel, group) {
  68626. var poyline = new Polyline({
  68627. z2: 20,
  68628. shape: {
  68629. points: points
  68630. },
  68631. style: lineStyleModel
  68632. });
  68633. group.add(poyline);
  68634. },
  68635. // render month line of one week points
  68636. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  68637. var coordSys = calendarModel.coordinateSystem;
  68638. date = coordSys.getDateInfo(date);
  68639. var points = [];
  68640. for (var i = 0; i < 7; i++) {
  68641. var tmpD = coordSys.getNextNDay(date.time, i);
  68642. var point = coordSys.dataToRect([tmpD.time], false);
  68643. points[2 * tmpD.day] = point.tl;
  68644. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  68645. }
  68646. return points;
  68647. },
  68648. _formatterLabel: function (formatter, params) {
  68649. if (typeof formatter === 'string' && formatter) {
  68650. return formatTplSimple(formatter, params);
  68651. }
  68652. if (typeof formatter === 'function') {
  68653. return formatter(params);
  68654. }
  68655. return params.nameMap;
  68656. },
  68657. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  68658. point = point.slice();
  68659. var aligns = ['center', 'bottom'];
  68660. if (position === 'bottom') {
  68661. point[1] += margin;
  68662. aligns = ['center', 'top'];
  68663. }
  68664. else if (position === 'left') {
  68665. point[0] -= margin;
  68666. }
  68667. else if (position === 'right') {
  68668. point[0] += margin;
  68669. aligns = ['center', 'top'];
  68670. }
  68671. else { // top
  68672. point[1] -= margin;
  68673. }
  68674. var rotate = 0;
  68675. if (position === 'left' || position === 'right') {
  68676. rotate = Math.PI / 2;
  68677. }
  68678. return {
  68679. rotation: rotate,
  68680. position: point,
  68681. style: {
  68682. textAlign: aligns[0],
  68683. textVerticalAlign: aligns[1]
  68684. }
  68685. };
  68686. },
  68687. // render year
  68688. _renderYearText: function (calendarModel, rangeData, orient, group) {
  68689. var yearLabel = calendarModel.getModel('yearLabel');
  68690. if (!yearLabel.get('show')) {
  68691. return;
  68692. }
  68693. var margin = yearLabel.get('margin');
  68694. var pos = yearLabel.get('position');
  68695. if (!pos) {
  68696. pos = orient !== 'horizontal' ? 'top' : 'left';
  68697. }
  68698. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  68699. var xc = (points[0][0] + points[1][0]) / 2;
  68700. var yc = (points[0][1] + points[1][1]) / 2;
  68701. var idx = orient === 'horizontal' ? 0 : 1;
  68702. var posPoints = {
  68703. top: [xc, points[idx][1]],
  68704. bottom: [xc, points[1 - idx][1]],
  68705. left: [points[1 - idx][0], yc],
  68706. right: [points[idx][0], yc]
  68707. };
  68708. var name = rangeData.start.y;
  68709. if (+rangeData.end.y > +rangeData.start.y) {
  68710. name = name + '-' + rangeData.end.y;
  68711. }
  68712. var formatter = yearLabel.get('formatter');
  68713. var params = {
  68714. start: rangeData.start.y,
  68715. end: rangeData.end.y,
  68716. nameMap: name
  68717. };
  68718. var content = this._formatterLabel(formatter, params);
  68719. var yearText = new Text({z2: 30});
  68720. setTextStyle(yearText.style, yearLabel, {text: content}),
  68721. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  68722. group.add(yearText);
  68723. },
  68724. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  68725. var align = 'left';
  68726. var vAlign = 'top';
  68727. var x = point[0];
  68728. var y = point[1];
  68729. if (orient === 'horizontal') {
  68730. y = y + margin;
  68731. if (isCenter) {
  68732. align = 'center';
  68733. }
  68734. if (position === 'start') {
  68735. vAlign = 'bottom';
  68736. }
  68737. }
  68738. else {
  68739. x = x + margin;
  68740. if (isCenter) {
  68741. vAlign = 'middle';
  68742. }
  68743. if (position === 'start') {
  68744. align = 'right';
  68745. }
  68746. }
  68747. return {
  68748. x: x,
  68749. y: y,
  68750. textAlign: align,
  68751. textVerticalAlign: vAlign
  68752. };
  68753. },
  68754. // render month and year text
  68755. _renderMonthText: function (calendarModel, orient, group) {
  68756. var monthLabel = calendarModel.getModel('monthLabel');
  68757. if (!monthLabel.get('show')) {
  68758. return;
  68759. }
  68760. var nameMap = monthLabel.get('nameMap');
  68761. var margin = monthLabel.get('margin');
  68762. var pos = monthLabel.get('position');
  68763. var align = monthLabel.get('align');
  68764. var termPoints = [this._tlpoints, this._blpoints];
  68765. if (isString(nameMap)) {
  68766. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  68767. }
  68768. var idx = pos === 'start' ? 0 : 1;
  68769. var axis = orient === 'horizontal' ? 0 : 1;
  68770. margin = pos === 'start' ? -margin : margin;
  68771. var isCenter = (align === 'center');
  68772. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  68773. var tmp = termPoints[idx][i].slice();
  68774. var firstDay = this._firstDayOfMonth[i];
  68775. if (isCenter) {
  68776. var firstDayPoints = this._firstDayPoints[i];
  68777. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  68778. }
  68779. var formatter = monthLabel.get('formatter');
  68780. var name = nameMap[+firstDay.m - 1];
  68781. var params = {
  68782. yyyy: firstDay.y,
  68783. yy: (firstDay.y + '').slice(2),
  68784. MM: firstDay.m,
  68785. M: +firstDay.m,
  68786. nameMap: name
  68787. };
  68788. var content = this._formatterLabel(formatter, params);
  68789. var monthText = new Text({z2: 30});
  68790. extend(
  68791. setTextStyle(monthText.style, monthLabel, {text: content}),
  68792. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  68793. );
  68794. group.add(monthText);
  68795. }
  68796. },
  68797. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  68798. var align = 'center';
  68799. var vAlign = 'middle';
  68800. var x = point[0];
  68801. var y = point[1];
  68802. var isStart = position === 'start';
  68803. if (orient === 'horizontal') {
  68804. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  68805. align = isStart ? 'right' : 'left';
  68806. }
  68807. else {
  68808. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  68809. vAlign = isStart ? 'bottom' : 'top';
  68810. }
  68811. return {
  68812. x: x,
  68813. y: y,
  68814. textAlign: align,
  68815. textVerticalAlign: vAlign
  68816. };
  68817. },
  68818. // render weeks
  68819. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  68820. var dayLabel = calendarModel.getModel('dayLabel');
  68821. if (!dayLabel.get('show')) {
  68822. return;
  68823. }
  68824. var coordSys = calendarModel.coordinateSystem;
  68825. var pos = dayLabel.get('position');
  68826. var nameMap = dayLabel.get('nameMap');
  68827. var margin = dayLabel.get('margin');
  68828. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  68829. if (isString(nameMap)) {
  68830. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  68831. }
  68832. var start = coordSys.getNextNDay(
  68833. rangeData.end.time, (7 - rangeData.lweek)
  68834. ).time;
  68835. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  68836. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  68837. if (pos === 'start') {
  68838. start = coordSys.getNextNDay(
  68839. rangeData.start.time, -(7 + rangeData.fweek)
  68840. ).time;
  68841. margin = -margin;
  68842. }
  68843. for (var i = 0; i < 7; i++) {
  68844. var tmpD = coordSys.getNextNDay(start, i);
  68845. var point = coordSys.dataToRect([tmpD.time], false).center;
  68846. var day = i;
  68847. day = Math.abs((i + firstDayOfWeek) % 7);
  68848. var weekText = new Text({z2: 30});
  68849. extend(
  68850. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  68851. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  68852. );
  68853. group.add(weekText);
  68854. }
  68855. }
  68856. });
  68857. /*
  68858. * Licensed to the Apache Software Foundation (ASF) under one
  68859. * or more contributor license agreements. See the NOTICE file
  68860. * distributed with this work for additional information
  68861. * regarding copyright ownership. The ASF licenses this file
  68862. * to you under the Apache License, Version 2.0 (the
  68863. * "License"); you may not use this file except in compliance
  68864. * with the License. You may obtain a copy of the License at
  68865. *
  68866. * http://www.apache.org/licenses/LICENSE-2.0
  68867. *
  68868. * Unless required by applicable law or agreed to in writing,
  68869. * software distributed under the License is distributed on an
  68870. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68871. * KIND, either express or implied. See the License for the
  68872. * specific language governing permissions and limitations
  68873. * under the License.
  68874. */
  68875. /**
  68876. * @file calendar.js
  68877. * @author dxh
  68878. */
  68879. /*
  68880. * Licensed to the Apache Software Foundation (ASF) under one
  68881. * or more contributor license agreements. See the NOTICE file
  68882. * distributed with this work for additional information
  68883. * regarding copyright ownership. The ASF licenses this file
  68884. * to you under the Apache License, Version 2.0 (the
  68885. * "License"); you may not use this file except in compliance
  68886. * with the License. You may obtain a copy of the License at
  68887. *
  68888. * http://www.apache.org/licenses/LICENSE-2.0
  68889. *
  68890. * Unless required by applicable law or agreed to in writing,
  68891. * software distributed under the License is distributed on an
  68892. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68893. * KIND, either express or implied. See the License for the
  68894. * specific language governing permissions and limitations
  68895. * under the License.
  68896. */
  68897. // Model
  68898. extendComponentModel({
  68899. type: 'title',
  68900. layoutMode: {type: 'box', ignoreSize: true},
  68901. defaultOption: {
  68902. // 一级层叠
  68903. zlevel: 0,
  68904. // 二级层叠
  68905. z: 6,
  68906. show: true,
  68907. text: '',
  68908. // 超链接跳转
  68909. // link: null,
  68910. // 仅支持self | blank
  68911. target: 'blank',
  68912. subtext: '',
  68913. // 超链接跳转
  68914. // sublink: null,
  68915. // 仅支持self | blank
  68916. subtarget: 'blank',
  68917. // 'center' ¦ 'left' ¦ 'right'
  68918. // ¦ {number}(x坐标,单位px)
  68919. left: 0,
  68920. // 'top' ¦ 'bottom' ¦ 'center'
  68921. // ¦ {number}(y坐标,单位px)
  68922. top: 0,
  68923. // 水平对齐
  68924. // 'auto' | 'left' | 'right' | 'center'
  68925. // 默认根据 left 的位置判断是左对齐还是右对齐
  68926. // textAlign: null
  68927. //
  68928. // 垂直对齐
  68929. // 'auto' | 'top' | 'bottom' | 'middle'
  68930. // 默认根据 top 位置判断是上对齐还是下对齐
  68931. // textBaseline: null
  68932. backgroundColor: 'rgba(0,0,0,0)',
  68933. // 标题边框颜色
  68934. borderColor: '#ccc',
  68935. // 标题边框线宽,单位px,默认为0(无边框)
  68936. borderWidth: 0,
  68937. // 标题内边距,单位px,默认各方向内边距为5,
  68938. // 接受数组分别设定上右下左边距,同css
  68939. padding: 5,
  68940. // 主副标题纵向间隔,单位px,默认为10,
  68941. itemGap: 10,
  68942. textStyle: {
  68943. fontSize: 18,
  68944. fontWeight: 'bolder',
  68945. color: '#333'
  68946. },
  68947. subtextStyle: {
  68948. color: '#aaa'
  68949. }
  68950. }
  68951. });
  68952. // View
  68953. extendComponentView({
  68954. type: 'title',
  68955. render: function (titleModel, ecModel, api) {
  68956. this.group.removeAll();
  68957. if (!titleModel.get('show')) {
  68958. return;
  68959. }
  68960. var group = this.group;
  68961. var textStyleModel = titleModel.getModel('textStyle');
  68962. var subtextStyleModel = titleModel.getModel('subtextStyle');
  68963. var textAlign = titleModel.get('textAlign');
  68964. var textBaseline = titleModel.get('textBaseline');
  68965. var textEl = new Text({
  68966. style: setTextStyle({}, textStyleModel, {
  68967. text: titleModel.get('text'),
  68968. textFill: textStyleModel.getTextColor()
  68969. }, {disableBox: true}),
  68970. z2: 10
  68971. });
  68972. var textRect = textEl.getBoundingRect();
  68973. var subText = titleModel.get('subtext');
  68974. var subTextEl = new Text({
  68975. style: setTextStyle({}, subtextStyleModel, {
  68976. text: subText,
  68977. textFill: subtextStyleModel.getTextColor(),
  68978. y: textRect.height + titleModel.get('itemGap'),
  68979. textVerticalAlign: 'top'
  68980. }, {disableBox: true}),
  68981. z2: 10
  68982. });
  68983. var link = titleModel.get('link');
  68984. var sublink = titleModel.get('sublink');
  68985. var triggerEvent = titleModel.get('triggerEvent', true);
  68986. textEl.silent = !link && !triggerEvent;
  68987. subTextEl.silent = !sublink && !triggerEvent;
  68988. if (link) {
  68989. textEl.on('click', function () {
  68990. window.open(link, '_' + titleModel.get('target'));
  68991. });
  68992. }
  68993. if (sublink) {
  68994. subTextEl.on('click', function () {
  68995. window.open(sublink, '_' + titleModel.get('subtarget'));
  68996. });
  68997. }
  68998. textEl.eventData = subTextEl.eventData = triggerEvent
  68999. ? {
  69000. componentType: 'title',
  69001. componentIndex: titleModel.componentIndex
  69002. }
  69003. : null;
  69004. group.add(textEl);
  69005. subText && group.add(subTextEl);
  69006. // If no subText, but add subTextEl, there will be an empty line.
  69007. var groupRect = group.getBoundingRect();
  69008. var layoutOption = titleModel.getBoxLayoutParams();
  69009. layoutOption.width = groupRect.width;
  69010. layoutOption.height = groupRect.height;
  69011. var layoutRect = getLayoutRect(
  69012. layoutOption, {
  69013. width: api.getWidth(),
  69014. height: api.getHeight()
  69015. }, titleModel.get('padding')
  69016. );
  69017. // Adjust text align based on position
  69018. if (!textAlign) {
  69019. // Align left if title is on the left. center and right is same
  69020. textAlign = titleModel.get('left') || titleModel.get('right');
  69021. if (textAlign === 'middle') {
  69022. textAlign = 'center';
  69023. }
  69024. // Adjust layout by text align
  69025. if (textAlign === 'right') {
  69026. layoutRect.x += layoutRect.width;
  69027. }
  69028. else if (textAlign === 'center') {
  69029. layoutRect.x += layoutRect.width / 2;
  69030. }
  69031. }
  69032. if (!textBaseline) {
  69033. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  69034. if (textBaseline === 'center') {
  69035. textBaseline = 'middle';
  69036. }
  69037. if (textBaseline === 'bottom') {
  69038. layoutRect.y += layoutRect.height;
  69039. }
  69040. else if (textBaseline === 'middle') {
  69041. layoutRect.y += layoutRect.height / 2;
  69042. }
  69043. textBaseline = textBaseline || 'top';
  69044. }
  69045. group.attr('position', [layoutRect.x, layoutRect.y]);
  69046. var alignStyle = {
  69047. textAlign: textAlign,
  69048. textVerticalAlign: textBaseline
  69049. };
  69050. textEl.setStyle(alignStyle);
  69051. subTextEl.setStyle(alignStyle);
  69052. // Render background
  69053. // Get groupRect again because textAlign has been changed
  69054. groupRect = group.getBoundingRect();
  69055. var padding = layoutRect.margin;
  69056. var style = titleModel.getItemStyle(['color', 'opacity']);
  69057. style.fill = titleModel.get('backgroundColor');
  69058. var rect = new Rect({
  69059. shape: {
  69060. x: groupRect.x - padding[3],
  69061. y: groupRect.y - padding[0],
  69062. width: groupRect.width + padding[1] + padding[3],
  69063. height: groupRect.height + padding[0] + padding[2],
  69064. r: titleModel.get('borderRadius')
  69065. },
  69066. style: style,
  69067. silent: true
  69068. });
  69069. subPixelOptimizeRect(rect);
  69070. group.add(rect);
  69071. }
  69072. });
  69073. /*
  69074. * Licensed to the Apache Software Foundation (ASF) under one
  69075. * or more contributor license agreements. See the NOTICE file
  69076. * distributed with this work for additional information
  69077. * regarding copyright ownership. The ASF licenses this file
  69078. * to you under the Apache License, Version 2.0 (the
  69079. * "License"); you may not use this file except in compliance
  69080. * with the License. You may obtain a copy of the License at
  69081. *
  69082. * http://www.apache.org/licenses/LICENSE-2.0
  69083. *
  69084. * Unless required by applicable law or agreed to in writing,
  69085. * software distributed under the License is distributed on an
  69086. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69087. * KIND, either express or implied. See the License for the
  69088. * specific language governing permissions and limitations
  69089. * under the License.
  69090. */
  69091. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  69092. // Default 'slider' when no type specified.
  69093. return 'slider';
  69094. });
  69095. /*
  69096. * Licensed to the Apache Software Foundation (ASF) under one
  69097. * or more contributor license agreements. See the NOTICE file
  69098. * distributed with this work for additional information
  69099. * regarding copyright ownership. The ASF licenses this file
  69100. * to you under the Apache License, Version 2.0 (the
  69101. * "License"); you may not use this file except in compliance
  69102. * with the License. You may obtain a copy of the License at
  69103. *
  69104. * http://www.apache.org/licenses/LICENSE-2.0
  69105. *
  69106. * Unless required by applicable law or agreed to in writing,
  69107. * software distributed under the License is distributed on an
  69108. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69109. * KIND, either express or implied. See the License for the
  69110. * specific language governing permissions and limitations
  69111. * under the License.
  69112. */
  69113. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  69114. // Supported coords.
  69115. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  69116. /**
  69117. * @param {string} coordType
  69118. * @return {boolean}
  69119. */
  69120. function isCoordSupported(coordType) {
  69121. return indexOf(COORDS, coordType) >= 0;
  69122. }
  69123. /**
  69124. * Create "each" method to iterate names.
  69125. *
  69126. * @pubilc
  69127. * @param {Array.<string>} names
  69128. * @param {Array.<string>=} attrs
  69129. * @return {Function}
  69130. */
  69131. function createNameEach(names, attrs) {
  69132. names = names.slice();
  69133. var capitalNames = map(names, capitalFirst);
  69134. attrs = (attrs || []).slice();
  69135. var capitalAttrs = map(attrs, capitalFirst);
  69136. return function (callback, context) {
  69137. each$1(names, function (name, index) {
  69138. var nameObj = {name: name, capital: capitalNames[index]};
  69139. for (var j = 0; j < attrs.length; j++) {
  69140. nameObj[attrs[j]] = name + capitalAttrs[j];
  69141. }
  69142. callback.call(context, nameObj);
  69143. });
  69144. };
  69145. }
  69146. /**
  69147. * Iterate each dimension name.
  69148. *
  69149. * @public
  69150. * @param {Function} callback The parameter is like:
  69151. * {
  69152. * name: 'angle',
  69153. * capital: 'Angle',
  69154. * axis: 'angleAxis',
  69155. * axisIndex: 'angleAixs',
  69156. * index: 'angleIndex'
  69157. * }
  69158. * @param {Object} context
  69159. */
  69160. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  69161. /**
  69162. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  69163. * dataZoomModels and 'links' make up one or more graphics.
  69164. * This function finds the graphic where the source dataZoomModel is in.
  69165. *
  69166. * @public
  69167. * @param {Function} forEachNode Node iterator.
  69168. * @param {Function} forEachEdgeType edgeType iterator
  69169. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  69170. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  69171. */
  69172. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  69173. return function (sourceNode) {
  69174. var result = {
  69175. nodes: [],
  69176. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  69177. };
  69178. forEachEdgeType(function (edgeType) {
  69179. result.records[edgeType.name] = {};
  69180. });
  69181. if (!sourceNode) {
  69182. return result;
  69183. }
  69184. absorb(sourceNode, result);
  69185. var existsLink;
  69186. do {
  69187. existsLink = false;
  69188. forEachNode(processSingleNode);
  69189. }
  69190. while (existsLink);
  69191. function processSingleNode(node) {
  69192. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  69193. absorb(node, result);
  69194. existsLink = true;
  69195. }
  69196. }
  69197. return result;
  69198. };
  69199. function isNodeAbsorded(node, result) {
  69200. return indexOf(result.nodes, node) >= 0;
  69201. }
  69202. function isLinked(node, result) {
  69203. var hasLink = false;
  69204. forEachEdgeType(function (edgeType) {
  69205. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  69206. result.records[edgeType.name][edgeId] && (hasLink = true);
  69207. });
  69208. });
  69209. return hasLink;
  69210. }
  69211. function absorb(node, result) {
  69212. result.nodes.push(node);
  69213. forEachEdgeType(function (edgeType) {
  69214. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  69215. result.records[edgeType.name][edgeId] = true;
  69216. });
  69217. });
  69218. }
  69219. }
  69220. /*
  69221. * Licensed to the Apache Software Foundation (ASF) under one
  69222. * or more contributor license agreements. See the NOTICE file
  69223. * distributed with this work for additional information
  69224. * regarding copyright ownership. The ASF licenses this file
  69225. * to you under the Apache License, Version 2.0 (the
  69226. * "License"); you may not use this file except in compliance
  69227. * with the License. You may obtain a copy of the License at
  69228. *
  69229. * http://www.apache.org/licenses/LICENSE-2.0
  69230. *
  69231. * Unless required by applicable law or agreed to in writing,
  69232. * software distributed under the License is distributed on an
  69233. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69234. * KIND, either express or implied. See the License for the
  69235. * specific language governing permissions and limitations
  69236. * under the License.
  69237. */
  69238. var each$22 = each$1;
  69239. var asc$1 = asc;
  69240. /**
  69241. * Operate single axis.
  69242. * One axis can only operated by one axis operator.
  69243. * Different dataZoomModels may be defined to operate the same axis.
  69244. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  69245. * So dataZoomModels share one axisProxy in that case.
  69246. *
  69247. * @class
  69248. */
  69249. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  69250. /**
  69251. * @private
  69252. * @type {string}
  69253. */
  69254. this._dimName = dimName;
  69255. /**
  69256. * @private
  69257. */
  69258. this._axisIndex = axisIndex;
  69259. /**
  69260. * @private
  69261. * @type {Array.<number>}
  69262. */
  69263. this._valueWindow;
  69264. /**
  69265. * @private
  69266. * @type {Array.<number>}
  69267. */
  69268. this._percentWindow;
  69269. /**
  69270. * @private
  69271. * @type {Array.<number>}
  69272. */
  69273. this._dataExtent;
  69274. /**
  69275. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  69276. * @private
  69277. * @type {Object}
  69278. */
  69279. this._minMaxSpan;
  69280. /**
  69281. * @readOnly
  69282. * @type {module: echarts/model/Global}
  69283. */
  69284. this.ecModel = ecModel;
  69285. /**
  69286. * @private
  69287. * @type {module: echarts/component/dataZoom/DataZoomModel}
  69288. */
  69289. this._dataZoomModel = dataZoomModel;
  69290. // /**
  69291. // * @readOnly
  69292. // * @private
  69293. // */
  69294. // this.hasSeriesStacked;
  69295. };
  69296. AxisProxy.prototype = {
  69297. constructor: AxisProxy,
  69298. /**
  69299. * Whether the axisProxy is hosted by dataZoomModel.
  69300. *
  69301. * @public
  69302. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69303. * @return {boolean}
  69304. */
  69305. hostedBy: function (dataZoomModel) {
  69306. return this._dataZoomModel === dataZoomModel;
  69307. },
  69308. /**
  69309. * @return {Array.<number>} Value can only be NaN or finite value.
  69310. */
  69311. getDataValueWindow: function () {
  69312. return this._valueWindow.slice();
  69313. },
  69314. /**
  69315. * @return {Array.<number>}
  69316. */
  69317. getDataPercentWindow: function () {
  69318. return this._percentWindow.slice();
  69319. },
  69320. /**
  69321. * @public
  69322. * @param {number} axisIndex
  69323. * @return {Array} seriesModels
  69324. */
  69325. getTargetSeriesModels: function () {
  69326. var seriesModels = [];
  69327. var ecModel = this.ecModel;
  69328. ecModel.eachSeries(function (seriesModel) {
  69329. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  69330. var dimName = this._dimName;
  69331. var axisModel = ecModel.queryComponents({
  69332. mainType: dimName + 'Axis',
  69333. index: seriesModel.get(dimName + 'AxisIndex'),
  69334. id: seriesModel.get(dimName + 'AxisId')
  69335. })[0];
  69336. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  69337. seriesModels.push(seriesModel);
  69338. }
  69339. }
  69340. }, this);
  69341. return seriesModels;
  69342. },
  69343. getAxisModel: function () {
  69344. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  69345. },
  69346. getOtherAxisModel: function () {
  69347. var axisDim = this._dimName;
  69348. var ecModel = this.ecModel;
  69349. var axisModel = this.getAxisModel();
  69350. var isCartesian = axisDim === 'x' || axisDim === 'y';
  69351. var otherAxisDim;
  69352. var coordSysIndexName;
  69353. if (isCartesian) {
  69354. coordSysIndexName = 'gridIndex';
  69355. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  69356. }
  69357. else {
  69358. coordSysIndexName = 'polarIndex';
  69359. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  69360. }
  69361. var foundOtherAxisModel;
  69362. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  69363. if ((otherAxisModel.get(coordSysIndexName) || 0)
  69364. === (axisModel.get(coordSysIndexName) || 0)
  69365. ) {
  69366. foundOtherAxisModel = otherAxisModel;
  69367. }
  69368. });
  69369. return foundOtherAxisModel;
  69370. },
  69371. getMinMaxSpan: function () {
  69372. return clone(this._minMaxSpan);
  69373. },
  69374. /**
  69375. * Only calculate by given range and this._dataExtent, do not change anything.
  69376. *
  69377. * @param {Object} opt
  69378. * @param {number} [opt.start]
  69379. * @param {number} [opt.end]
  69380. * @param {number} [opt.startValue]
  69381. * @param {number} [opt.endValue]
  69382. */
  69383. calculateDataWindow: function (opt) {
  69384. var dataExtent = this._dataExtent;
  69385. var axisModel = this.getAxisModel();
  69386. var scale = axisModel.axis.scale;
  69387. var rangePropMode = this._dataZoomModel.getRangePropMode();
  69388. var percentExtent = [0, 100];
  69389. var percentWindow = [
  69390. opt.start,
  69391. opt.end
  69392. ];
  69393. var valueWindow = [];
  69394. each$22(['startValue', 'endValue'], function (prop) {
  69395. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  69396. });
  69397. // Normalize bound.
  69398. each$22([0, 1], function (idx) {
  69399. var boundValue = valueWindow[idx];
  69400. var boundPercent = percentWindow[idx];
  69401. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  69402. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  69403. // for cases that a dataZoom component controls multiple axes with different
  69404. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  69405. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  69406. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  69407. // accurately (because all of values that are overflow the `dataExtent` will
  69408. // be calculated to percent '100%'). So we have to use
  69409. // `dataZoom.getRangePropMode()` to mark which prop is used.
  69410. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  69411. // it remains its original value.
  69412. if (rangePropMode[idx] === 'percent') {
  69413. if (boundPercent == null) {
  69414. boundPercent = percentExtent[idx];
  69415. }
  69416. // Use scale.parse to math round for category or time axis.
  69417. boundValue = scale.parse(linearMap(
  69418. boundPercent, percentExtent, dataExtent, true
  69419. ));
  69420. }
  69421. else {
  69422. // Calculating `percent` from `value` may be not accurate, because
  69423. // This calculation can not be inversed, because all of values that
  69424. // are overflow the `dataExtent` will be calculated to percent '100%'
  69425. boundPercent = linearMap(
  69426. boundValue, dataExtent, percentExtent, true
  69427. );
  69428. }
  69429. // valueWindow[idx] = round(boundValue);
  69430. // percentWindow[idx] = round(boundPercent);
  69431. valueWindow[idx] = boundValue;
  69432. percentWindow[idx] = boundPercent;
  69433. });
  69434. return {
  69435. valueWindow: asc$1(valueWindow),
  69436. percentWindow: asc$1(percentWindow)
  69437. };
  69438. },
  69439. /**
  69440. * Notice: reset should not be called before series.restoreData() called,
  69441. * so it is recommanded to be called in "process stage" but not "model init
  69442. * stage".
  69443. *
  69444. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69445. */
  69446. reset: function (dataZoomModel) {
  69447. if (dataZoomModel !== this._dataZoomModel) {
  69448. return;
  69449. }
  69450. var targetSeries = this.getTargetSeriesModels();
  69451. // Culculate data window and data extent, and record them.
  69452. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  69453. // this.hasSeriesStacked = false;
  69454. // each(targetSeries, function (series) {
  69455. // var data = series.getData();
  69456. // var dataDim = data.mapDimension(this._dimName);
  69457. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  69458. // if (stackedDimension && stackedDimension === dataDim) {
  69459. // this.hasSeriesStacked = true;
  69460. // }
  69461. // }, this);
  69462. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  69463. this._valueWindow = dataWindow.valueWindow;
  69464. this._percentWindow = dataWindow.percentWindow;
  69465. setMinMaxSpan(this);
  69466. // Update axis setting then.
  69467. setAxisModel(this);
  69468. },
  69469. /**
  69470. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69471. */
  69472. restore: function (dataZoomModel) {
  69473. if (dataZoomModel !== this._dataZoomModel) {
  69474. return;
  69475. }
  69476. this._valueWindow = this._percentWindow = null;
  69477. setAxisModel(this, true);
  69478. },
  69479. /**
  69480. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  69481. */
  69482. filterData: function (dataZoomModel, api) {
  69483. if (dataZoomModel !== this._dataZoomModel) {
  69484. return;
  69485. }
  69486. var axisDim = this._dimName;
  69487. var seriesModels = this.getTargetSeriesModels();
  69488. var filterMode = dataZoomModel.get('filterMode');
  69489. var valueWindow = this._valueWindow;
  69490. if (filterMode === 'none') {
  69491. return;
  69492. }
  69493. // FIXME
  69494. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  69495. // with NaN data, NaN will be filtered and stack will be wrong.
  69496. // So we need to force the mode to be set empty.
  69497. // In fect, it is not a big deal that do not support filterMode-'filter'
  69498. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  69499. // selection" some day, which might need "adapt to data extent on the
  69500. // otherAxis", which is disabled by filterMode-'empty'.
  69501. // But currently, stack has been fixed to based on value but not index,
  69502. // so this is not an issue any more.
  69503. // var otherAxisModel = this.getOtherAxisModel();
  69504. // if (dataZoomModel.get('$fromToolbox')
  69505. // && otherAxisModel
  69506. // && otherAxisModel.hasSeriesStacked
  69507. // ) {
  69508. // filterMode = 'empty';
  69509. // }
  69510. // TODO
  69511. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  69512. each$22(seriesModels, function (seriesModel) {
  69513. var seriesData = seriesModel.getData();
  69514. var dataDims = seriesData.mapDimension(axisDim, true);
  69515. if (!dataDims.length) {
  69516. return;
  69517. }
  69518. if (filterMode === 'weakFilter') {
  69519. seriesData.filterSelf(function (dataIndex) {
  69520. var leftOut;
  69521. var rightOut;
  69522. var hasValue;
  69523. for (var i = 0; i < dataDims.length; i++) {
  69524. var value = seriesData.get(dataDims[i], dataIndex);
  69525. var thisHasValue = !isNaN(value);
  69526. var thisLeftOut = value < valueWindow[0];
  69527. var thisRightOut = value > valueWindow[1];
  69528. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  69529. return true;
  69530. }
  69531. thisHasValue && (hasValue = true);
  69532. thisLeftOut && (leftOut = true);
  69533. thisRightOut && (rightOut = true);
  69534. }
  69535. // If both left out and right out, do not filter.
  69536. return hasValue && leftOut && rightOut;
  69537. });
  69538. }
  69539. else {
  69540. each$22(dataDims, function (dim) {
  69541. if (filterMode === 'empty') {
  69542. seriesModel.setData(
  69543. seriesData.map(dim, function (value) {
  69544. return !isInWindow(value) ? NaN : value;
  69545. })
  69546. );
  69547. }
  69548. else {
  69549. var range = {};
  69550. range[dim] = valueWindow;
  69551. // console.time('select');
  69552. seriesData.selectRange(range);
  69553. // console.timeEnd('select');
  69554. }
  69555. });
  69556. }
  69557. each$22(dataDims, function (dim) {
  69558. seriesData.setApproximateExtent(valueWindow, dim);
  69559. });
  69560. });
  69561. function isInWindow(value) {
  69562. return value >= valueWindow[0] && value <= valueWindow[1];
  69563. }
  69564. }
  69565. };
  69566. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  69567. var dataExtent = [Infinity, -Infinity];
  69568. each$22(seriesModels, function (seriesModel) {
  69569. var seriesData = seriesModel.getData();
  69570. if (seriesData) {
  69571. each$22(seriesData.mapDimension(axisDim, true), function (dim) {
  69572. var seriesExtent = seriesData.getApproximateExtent(dim);
  69573. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  69574. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  69575. });
  69576. }
  69577. });
  69578. if (dataExtent[1] < dataExtent[0]) {
  69579. dataExtent = [NaN, NaN];
  69580. }
  69581. // It is important to get "consistent" extent when more then one axes is
  69582. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  69583. // when zooming. But it is difficult to know what is "consistent", considering
  69584. // axes have different type or even different meanings (For example, two
  69585. // time axes are used to compare data of the same date in different years).
  69586. // So basically dataZoom just obtains extent by series.data (in category axis
  69587. // extent can be obtained from axis.data).
  69588. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  69589. // consistent.
  69590. fixExtentByAxis(axisProxy, dataExtent);
  69591. return dataExtent;
  69592. }
  69593. function fixExtentByAxis(axisProxy, dataExtent) {
  69594. var axisModel = axisProxy.getAxisModel();
  69595. var min = axisModel.getMin(true);
  69596. // For category axis, if min/max/scale are not set, extent is determined
  69597. // by axis.data by default.
  69598. var isCategoryAxis = axisModel.get('type') === 'category';
  69599. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  69600. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  69601. dataExtent[0] = min;
  69602. }
  69603. else if (isCategoryAxis) {
  69604. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  69605. }
  69606. var max = axisModel.getMax(true);
  69607. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  69608. dataExtent[1] = max;
  69609. }
  69610. else if (isCategoryAxis) {
  69611. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  69612. }
  69613. if (!axisModel.get('scale', true)) {
  69614. dataExtent[0] > 0 && (dataExtent[0] = 0);
  69615. dataExtent[1] < 0 && (dataExtent[1] = 0);
  69616. }
  69617. // For value axis, if min/max/scale are not set, we just use the extent obtained
  69618. // by series data, which may be a little different from the extent calculated by
  69619. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  69620. // little when zooming. So it will not be fixed until some users require it strongly.
  69621. return dataExtent;
  69622. }
  69623. function setAxisModel(axisProxy, isRestore) {
  69624. var axisModel = axisProxy.getAxisModel();
  69625. var percentWindow = axisProxy._percentWindow;
  69626. var valueWindow = axisProxy._valueWindow;
  69627. if (!percentWindow) {
  69628. return;
  69629. }
  69630. // [0, 500]: arbitrary value, guess axis extent.
  69631. var precision = getPixelPrecision(valueWindow, [0, 500]);
  69632. precision = Math.min(precision, 20);
  69633. // isRestore or isFull
  69634. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  69635. axisModel.setRange(
  69636. useOrigin ? null : +valueWindow[0].toFixed(precision),
  69637. useOrigin ? null : +valueWindow[1].toFixed(precision)
  69638. );
  69639. }
  69640. function setMinMaxSpan(axisProxy) {
  69641. var minMaxSpan = axisProxy._minMaxSpan = {};
  69642. var dataZoomModel = axisProxy._dataZoomModel;
  69643. each$22(['min', 'max'], function (minMax) {
  69644. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  69645. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  69646. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  69647. if (valueSpan != null) {
  69648. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  69649. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  69650. if (valueSpan != null) {
  69651. var dataExtent = axisProxy._dataExtent;
  69652. minMaxSpan[minMax + 'Span'] = linearMap(
  69653. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  69654. );
  69655. }
  69656. }
  69657. });
  69658. }
  69659. /*
  69660. * Licensed to the Apache Software Foundation (ASF) under one
  69661. * or more contributor license agreements. See the NOTICE file
  69662. * distributed with this work for additional information
  69663. * regarding copyright ownership. The ASF licenses this file
  69664. * to you under the Apache License, Version 2.0 (the
  69665. * "License"); you may not use this file except in compliance
  69666. * with the License. You may obtain a copy of the License at
  69667. *
  69668. * http://www.apache.org/licenses/LICENSE-2.0
  69669. *
  69670. * Unless required by applicable law or agreed to in writing,
  69671. * software distributed under the License is distributed on an
  69672. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69673. * KIND, either express or implied. See the License for the
  69674. * specific language governing permissions and limitations
  69675. * under the License.
  69676. */
  69677. var each$21 = each$1;
  69678. var eachAxisDim = eachAxisDim$1;
  69679. var DataZoomModel = extendComponentModel({
  69680. type: 'dataZoom',
  69681. dependencies: [
  69682. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  69683. ],
  69684. /**
  69685. * @protected
  69686. */
  69687. defaultOption: {
  69688. zlevel: 0,
  69689. z: 4, // Higher than normal component (z: 2).
  69690. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  69691. xAxisIndex: null, // Default the first horizontal category axis.
  69692. yAxisIndex: null, // Default the first vertical category axis.
  69693. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  69694. // 'filter': data items which are out of window will be removed. This option is
  69695. // applicable when filtering outliers. For each data item, it will be
  69696. // filtered if one of the relevant dimensions is out of the window.
  69697. // 'weakFilter': data items which are out of window will be removed. This option
  69698. // is applicable when filtering outliers. For each data item, it will be
  69699. // filtered only if all of the relevant dimensions are out of the same
  69700. // side of the window.
  69701. // 'empty': data items which are out of window will be set to empty.
  69702. // This option is applicable when user should not neglect
  69703. // that there are some data items out of window.
  69704. // 'none': Do not filter.
  69705. // Taking line chart as an example, line will be broken in
  69706. // the filtered points when filterModel is set to 'empty', but
  69707. // be connected when set to 'filter'.
  69708. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  69709. // default 100. Do not throttle when use null/undefined.
  69710. // If animation === true and animationDurationUpdate > 0,
  69711. // default value is 100, otherwise 20.
  69712. start: 0, // Start percent. 0 ~ 100
  69713. end: 100, // End percent. 0 ~ 100
  69714. startValue: null, // Start value. If startValue specified, start is ignored.
  69715. endValue: null, // End value. If endValue specified, end is ignored.
  69716. minSpan: null, // 0 ~ 100
  69717. maxSpan: null, // 0 ~ 100
  69718. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  69719. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  69720. rangeMode: null // Array, can be 'value' or 'percent'.
  69721. },
  69722. /**
  69723. * @override
  69724. */
  69725. init: function (option, parentModel, ecModel) {
  69726. /**
  69727. * key like x_0, y_1
  69728. * @private
  69729. * @type {Object}
  69730. */
  69731. this._dataIntervalByAxis = {};
  69732. /**
  69733. * @private
  69734. */
  69735. this._dataInfo = {};
  69736. /**
  69737. * key like x_0, y_1
  69738. * @private
  69739. */
  69740. this._axisProxies = {};
  69741. /**
  69742. * @readOnly
  69743. */
  69744. this.textStyleModel;
  69745. /**
  69746. * @private
  69747. */
  69748. this._autoThrottle = true;
  69749. /**
  69750. * 'percent' or 'value'
  69751. * @private
  69752. */
  69753. this._rangePropMode = ['percent', 'percent'];
  69754. var rawOption = retrieveRaw(option);
  69755. this.mergeDefaultAndTheme(option, ecModel);
  69756. this.doInit(rawOption);
  69757. },
  69758. /**
  69759. * @override
  69760. */
  69761. mergeOption: function (newOption) {
  69762. var rawOption = retrieveRaw(newOption);
  69763. //FIX #2591
  69764. merge(this.option, newOption, true);
  69765. this.doInit(rawOption);
  69766. },
  69767. /**
  69768. * @protected
  69769. */
  69770. doInit: function (rawOption) {
  69771. var thisOption = this.option;
  69772. // Disable realtime view update if canvas is not supported.
  69773. if (!env$1.canvasSupported) {
  69774. thisOption.realtime = false;
  69775. }
  69776. this._setDefaultThrottle(rawOption);
  69777. updateRangeUse(this, rawOption);
  69778. each$21([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  69779. // start/end has higher priority over startValue/endValue if they
  69780. // both set, but we should make chart.setOption({endValue: 1000})
  69781. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  69782. if (this._rangePropMode[index] === 'value') {
  69783. thisOption[names[0]] = null;
  69784. }
  69785. // Otherwise do nothing and use the merge result.
  69786. }, this);
  69787. this.textStyleModel = this.getModel('textStyle');
  69788. this._resetTarget();
  69789. this._giveAxisProxies();
  69790. },
  69791. /**
  69792. * @private
  69793. */
  69794. _giveAxisProxies: function () {
  69795. var axisProxies = this._axisProxies;
  69796. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  69797. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  69798. // If exists, share axisProxy with other dataZoomModels.
  69799. var axisProxy = axisModel.__dzAxisProxy || (
  69800. // Use the first dataZoomModel as the main model of axisProxy.
  69801. axisModel.__dzAxisProxy = new AxisProxy(
  69802. dimNames.name, axisIndex, this, ecModel
  69803. )
  69804. );
  69805. // FIXME
  69806. // dispose __dzAxisProxy
  69807. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  69808. }, this);
  69809. },
  69810. /**
  69811. * @private
  69812. */
  69813. _resetTarget: function () {
  69814. var thisOption = this.option;
  69815. var autoMode = this._judgeAutoMode();
  69816. eachAxisDim(function (dimNames) {
  69817. var axisIndexName = dimNames.axisIndex;
  69818. thisOption[axisIndexName] = normalizeToArray(
  69819. thisOption[axisIndexName]
  69820. );
  69821. }, this);
  69822. if (autoMode === 'axisIndex') {
  69823. this._autoSetAxisIndex();
  69824. }
  69825. else if (autoMode === 'orient') {
  69826. this._autoSetOrient();
  69827. }
  69828. },
  69829. /**
  69830. * @private
  69831. */
  69832. _judgeAutoMode: function () {
  69833. // Auto set only works for setOption at the first time.
  69834. // The following is user's reponsibility. So using merged
  69835. // option is OK.
  69836. var thisOption = this.option;
  69837. var hasIndexSpecified = false;
  69838. eachAxisDim(function (dimNames) {
  69839. // When user set axisIndex as a empty array, we think that user specify axisIndex
  69840. // but do not want use auto mode. Because empty array may be encountered when
  69841. // some error occured.
  69842. if (thisOption[dimNames.axisIndex] != null) {
  69843. hasIndexSpecified = true;
  69844. }
  69845. }, this);
  69846. var orient = thisOption.orient;
  69847. if (orient == null && hasIndexSpecified) {
  69848. return 'orient';
  69849. }
  69850. else if (!hasIndexSpecified) {
  69851. if (orient == null) {
  69852. thisOption.orient = 'horizontal';
  69853. }
  69854. return 'axisIndex';
  69855. }
  69856. },
  69857. /**
  69858. * @private
  69859. */
  69860. _autoSetAxisIndex: function () {
  69861. var autoAxisIndex = true;
  69862. var orient = this.get('orient', true);
  69863. var thisOption = this.option;
  69864. var dependentModels = this.dependentModels;
  69865. if (autoAxisIndex) {
  69866. // Find axis that parallel to dataZoom as default.
  69867. var dimName = orient === 'vertical' ? 'y' : 'x';
  69868. if (dependentModels[dimName + 'Axis'].length) {
  69869. thisOption[dimName + 'AxisIndex'] = [0];
  69870. autoAxisIndex = false;
  69871. }
  69872. else {
  69873. each$21(dependentModels.singleAxis, function (singleAxisModel) {
  69874. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  69875. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  69876. autoAxisIndex = false;
  69877. }
  69878. });
  69879. }
  69880. }
  69881. if (autoAxisIndex) {
  69882. // Find the first category axis as default. (consider polar)
  69883. eachAxisDim(function (dimNames) {
  69884. if (!autoAxisIndex) {
  69885. return;
  69886. }
  69887. var axisIndices = [];
  69888. var axisModels = this.dependentModels[dimNames.axis];
  69889. if (axisModels.length && !axisIndices.length) {
  69890. for (var i = 0, len = axisModels.length; i < len; i++) {
  69891. if (axisModels[i].get('type') === 'category') {
  69892. axisIndices.push(i);
  69893. }
  69894. }
  69895. }
  69896. thisOption[dimNames.axisIndex] = axisIndices;
  69897. if (axisIndices.length) {
  69898. autoAxisIndex = false;
  69899. }
  69900. }, this);
  69901. }
  69902. if (autoAxisIndex) {
  69903. // FIXME
  69904. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  69905. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  69906. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  69907. // dataZoom component auto adopts series that reference to
  69908. // both xAxis and yAxis which type is 'value'.
  69909. this.ecModel.eachSeries(function (seriesModel) {
  69910. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  69911. eachAxisDim(function (dimNames) {
  69912. var axisIndices = thisOption[dimNames.axisIndex];
  69913. var axisIndex = seriesModel.get(dimNames.axisIndex);
  69914. var axisId = seriesModel.get(dimNames.axisId);
  69915. var axisModel = seriesModel.ecModel.queryComponents({
  69916. mainType: dimNames.axis,
  69917. index: axisIndex,
  69918. id: axisId
  69919. })[0];
  69920. if (__DEV__) {
  69921. if (!axisModel) {
  69922. throw new Error(
  69923. dimNames.axis + ' "' + retrieve(
  69924. axisIndex,
  69925. axisId,
  69926. 0
  69927. ) + '" not found'
  69928. );
  69929. }
  69930. }
  69931. axisIndex = axisModel.componentIndex;
  69932. if (indexOf(axisIndices, axisIndex) < 0) {
  69933. axisIndices.push(axisIndex);
  69934. }
  69935. });
  69936. }
  69937. }, this);
  69938. }
  69939. },
  69940. /**
  69941. * @private
  69942. */
  69943. _autoSetOrient: function () {
  69944. var dim;
  69945. // Find the first axis
  69946. this.eachTargetAxis(function (dimNames) {
  69947. !dim && (dim = dimNames.name);
  69948. }, this);
  69949. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  69950. },
  69951. /**
  69952. * @private
  69953. */
  69954. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  69955. // FIXME
  69956. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  69957. // 例如series.type === scatter时。
  69958. var is = true;
  69959. eachAxisDim(function (dimNames) {
  69960. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  69961. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  69962. if (!axisModel || axisModel.get('type') !== axisType) {
  69963. is = false;
  69964. }
  69965. }, this);
  69966. return is;
  69967. },
  69968. /**
  69969. * @private
  69970. */
  69971. _setDefaultThrottle: function (rawOption) {
  69972. // When first time user set throttle, auto throttle ends.
  69973. if (rawOption.hasOwnProperty('throttle')) {
  69974. this._autoThrottle = false;
  69975. }
  69976. if (this._autoThrottle) {
  69977. var globalOption = this.ecModel.option;
  69978. this.option.throttle
  69979. = (globalOption.animation && globalOption.animationDurationUpdate > 0)
  69980. ? 100 : 20;
  69981. }
  69982. },
  69983. /**
  69984. * @public
  69985. */
  69986. getFirstTargetAxisModel: function () {
  69987. var firstAxisModel;
  69988. eachAxisDim(function (dimNames) {
  69989. if (firstAxisModel == null) {
  69990. var indices = this.get(dimNames.axisIndex);
  69991. if (indices.length) {
  69992. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  69993. }
  69994. }
  69995. }, this);
  69996. return firstAxisModel;
  69997. },
  69998. /**
  69999. * @public
  70000. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  70001. */
  70002. eachTargetAxis: function (callback, context) {
  70003. var ecModel = this.ecModel;
  70004. eachAxisDim(function (dimNames) {
  70005. each$21(
  70006. this.get(dimNames.axisIndex),
  70007. function (axisIndex) {
  70008. callback.call(context, dimNames, axisIndex, this, ecModel);
  70009. },
  70010. this
  70011. );
  70012. }, this);
  70013. },
  70014. /**
  70015. * @param {string} dimName
  70016. * @param {number} axisIndex
  70017. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  70018. */
  70019. getAxisProxy: function (dimName, axisIndex) {
  70020. return this._axisProxies[dimName + '_' + axisIndex];
  70021. },
  70022. /**
  70023. * @param {string} dimName
  70024. * @param {number} axisIndex
  70025. * @return {module:echarts/model/Model} If not found, return null/undefined.
  70026. */
  70027. getAxisModel: function (dimName, axisIndex) {
  70028. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  70029. return axisProxy && axisProxy.getAxisModel();
  70030. },
  70031. /**
  70032. * If not specified, set to undefined.
  70033. *
  70034. * @public
  70035. * @param {Object} opt
  70036. * @param {number} [opt.start]
  70037. * @param {number} [opt.end]
  70038. * @param {number} [opt.startValue]
  70039. * @param {number} [opt.endValue]
  70040. * @param {boolean} [ignoreUpdateRangeUsg=false]
  70041. */
  70042. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  70043. var option = this.option;
  70044. each$21([['start', 'startValue'], ['end', 'endValue']], function (names) {
  70045. // If only one of 'start' and 'startValue' is not null/undefined, the other
  70046. // should be cleared, which enable clear the option.
  70047. // If both of them are not set, keep option with the original value, which
  70048. // enable use only set start but not set end when calling `dispatchAction`.
  70049. // The same as 'end' and 'endValue'.
  70050. if (opt[names[0]] != null || opt[names[1]] != null) {
  70051. option[names[0]] = opt[names[0]];
  70052. option[names[1]] = opt[names[1]];
  70053. }
  70054. }, this);
  70055. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  70056. },
  70057. /**
  70058. * @public
  70059. * @return {Array.<number>} [startPercent, endPercent]
  70060. */
  70061. getPercentRange: function () {
  70062. var axisProxy = this.findRepresentativeAxisProxy();
  70063. if (axisProxy) {
  70064. return axisProxy.getDataPercentWindow();
  70065. }
  70066. },
  70067. /**
  70068. * @public
  70069. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  70070. *
  70071. * @param {string} [axisDimName]
  70072. * @param {number} [axisIndex]
  70073. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  70074. */
  70075. getValueRange: function (axisDimName, axisIndex) {
  70076. if (axisDimName == null && axisIndex == null) {
  70077. var axisProxy = this.findRepresentativeAxisProxy();
  70078. if (axisProxy) {
  70079. return axisProxy.getDataValueWindow();
  70080. }
  70081. }
  70082. else {
  70083. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  70084. }
  70085. },
  70086. /**
  70087. * @public
  70088. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  70089. * corresponding to the axisModel
  70090. * @return {module:echarts/component/dataZoom/AxisProxy}
  70091. */
  70092. findRepresentativeAxisProxy: function (axisModel) {
  70093. if (axisModel) {
  70094. return axisModel.__dzAxisProxy;
  70095. }
  70096. // Find the first hosted axisProxy
  70097. var axisProxies = this._axisProxies;
  70098. for (var key in axisProxies) {
  70099. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  70100. return axisProxies[key];
  70101. }
  70102. }
  70103. // If no hosted axis find not hosted axisProxy.
  70104. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  70105. // and the option.start or option.end settings are different. The percentRange
  70106. // should follow axisProxy.
  70107. // (We encounter this problem in toolbox data zoom.)
  70108. for (var key in axisProxies) {
  70109. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  70110. return axisProxies[key];
  70111. }
  70112. }
  70113. },
  70114. /**
  70115. * @return {Array.<string>}
  70116. */
  70117. getRangePropMode: function () {
  70118. return this._rangePropMode.slice();
  70119. }
  70120. });
  70121. function retrieveRaw(option) {
  70122. var ret = {};
  70123. each$21(
  70124. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  70125. function (name) {
  70126. option.hasOwnProperty(name) && (ret[name] = option[name]);
  70127. }
  70128. );
  70129. return ret;
  70130. }
  70131. function updateRangeUse(dataZoomModel, rawOption) {
  70132. var rangePropMode = dataZoomModel._rangePropMode;
  70133. var rangeModeInOption = dataZoomModel.get('rangeMode');
  70134. each$21([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  70135. var percentSpecified = rawOption[names[0]] != null;
  70136. var valueSpecified = rawOption[names[1]] != null;
  70137. if (percentSpecified && !valueSpecified) {
  70138. rangePropMode[index] = 'percent';
  70139. }
  70140. else if (!percentSpecified && valueSpecified) {
  70141. rangePropMode[index] = 'value';
  70142. }
  70143. else if (rangeModeInOption) {
  70144. rangePropMode[index] = rangeModeInOption[index];
  70145. }
  70146. else if (percentSpecified) { // percentSpecified && valueSpecified
  70147. rangePropMode[index] = 'percent';
  70148. }
  70149. // else remain its original setting.
  70150. });
  70151. }
  70152. /*
  70153. * Licensed to the Apache Software Foundation (ASF) under one
  70154. * or more contributor license agreements. See the NOTICE file
  70155. * distributed with this work for additional information
  70156. * regarding copyright ownership. The ASF licenses this file
  70157. * to you under the Apache License, Version 2.0 (the
  70158. * "License"); you may not use this file except in compliance
  70159. * with the License. You may obtain a copy of the License at
  70160. *
  70161. * http://www.apache.org/licenses/LICENSE-2.0
  70162. *
  70163. * Unless required by applicable law or agreed to in writing,
  70164. * software distributed under the License is distributed on an
  70165. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70166. * KIND, either express or implied. See the License for the
  70167. * specific language governing permissions and limitations
  70168. * under the License.
  70169. */
  70170. var DataZoomView = Component.extend({
  70171. type: 'dataZoom',
  70172. render: function (dataZoomModel, ecModel, api, payload) {
  70173. this.dataZoomModel = dataZoomModel;
  70174. this.ecModel = ecModel;
  70175. this.api = api;
  70176. },
  70177. /**
  70178. * Find the first target coordinate system.
  70179. *
  70180. * @protected
  70181. * @return {Object} {
  70182. * grid: [
  70183. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  70184. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  70185. * ...
  70186. * ], // cartesians must not be null/undefined.
  70187. * polar: [
  70188. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  70189. * ...
  70190. * ], // polars must not be null/undefined.
  70191. * singleAxis: [
  70192. * {model: coord0, axisModels: [], coordIndex: 0}
  70193. * ]
  70194. */
  70195. getTargetCoordInfo: function () {
  70196. var dataZoomModel = this.dataZoomModel;
  70197. var ecModel = this.ecModel;
  70198. var coordSysLists = {};
  70199. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  70200. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  70201. if (axisModel) {
  70202. var coordModel = axisModel.getCoordSysModel();
  70203. coordModel && save(
  70204. coordModel,
  70205. axisModel,
  70206. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  70207. coordModel.componentIndex
  70208. );
  70209. }
  70210. }, this);
  70211. function save(coordModel, axisModel, store, coordIndex) {
  70212. var item;
  70213. for (var i = 0; i < store.length; i++) {
  70214. if (store[i].model === coordModel) {
  70215. item = store[i];
  70216. break;
  70217. }
  70218. }
  70219. if (!item) {
  70220. store.push(item = {
  70221. model: coordModel, axisModels: [], coordIndex: coordIndex
  70222. });
  70223. }
  70224. item.axisModels.push(axisModel);
  70225. }
  70226. return coordSysLists;
  70227. }
  70228. });
  70229. /*
  70230. * Licensed to the Apache Software Foundation (ASF) under one
  70231. * or more contributor license agreements. See the NOTICE file
  70232. * distributed with this work for additional information
  70233. * regarding copyright ownership. The ASF licenses this file
  70234. * to you under the Apache License, Version 2.0 (the
  70235. * "License"); you may not use this file except in compliance
  70236. * with the License. You may obtain a copy of the License at
  70237. *
  70238. * http://www.apache.org/licenses/LICENSE-2.0
  70239. *
  70240. * Unless required by applicable law or agreed to in writing,
  70241. * software distributed under the License is distributed on an
  70242. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70243. * KIND, either express or implied. See the License for the
  70244. * specific language governing permissions and limitations
  70245. * under the License.
  70246. */
  70247. var SliderZoomModel = DataZoomModel.extend({
  70248. type: 'dataZoom.slider',
  70249. layoutMode: 'box',
  70250. /**
  70251. * @protected
  70252. */
  70253. defaultOption: {
  70254. show: true,
  70255. // ph => placeholder. Using placehoder here because
  70256. // deault value can only be drived in view stage.
  70257. right: 'ph', // Default align to grid rect.
  70258. top: 'ph', // Default align to grid rect.
  70259. width: 'ph', // Default align to grid rect.
  70260. height: 'ph', // Default align to grid rect.
  70261. left: null, // Default align to grid rect.
  70262. bottom: null, // Default align to grid rect.
  70263. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  70264. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  70265. // highest priority, remain for compatibility of
  70266. // previous version, but not recommended any more.
  70267. dataBackground: {
  70268. lineStyle: {
  70269. color: '#2f4554',
  70270. width: 0.5,
  70271. opacity: 0.3
  70272. },
  70273. areaStyle: {
  70274. color: 'rgba(47,69,84,0.3)',
  70275. opacity: 0.3
  70276. }
  70277. },
  70278. borderColor: '#ddd', // border color of the box. For compatibility,
  70279. // if dataBackgroundColor is set, borderColor
  70280. // is ignored.
  70281. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  70282. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  70283. // 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',
  70284. /* eslint-disable */
  70285. 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',
  70286. /* eslint-enable */
  70287. // Percent of the slider height
  70288. handleSize: '100%',
  70289. handleStyle: {
  70290. color: '#a7b7cc'
  70291. },
  70292. labelPrecision: null,
  70293. labelFormatter: null,
  70294. showDetail: true,
  70295. showDataShadow: 'auto', // Default auto decision.
  70296. realtime: true,
  70297. zoomLock: false, // Whether disable zoom.
  70298. textStyle: {
  70299. color: '#333'
  70300. }
  70301. }
  70302. });
  70303. /*
  70304. * Licensed to the Apache Software Foundation (ASF) under one
  70305. * or more contributor license agreements. See the NOTICE file
  70306. * distributed with this work for additional information
  70307. * regarding copyright ownership. The ASF licenses this file
  70308. * to you under the Apache License, Version 2.0 (the
  70309. * "License"); you may not use this file except in compliance
  70310. * with the License. You may obtain a copy of the License at
  70311. *
  70312. * http://www.apache.org/licenses/LICENSE-2.0
  70313. *
  70314. * Unless required by applicable law or agreed to in writing,
  70315. * software distributed under the License is distributed on an
  70316. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70317. * KIND, either express or implied. See the License for the
  70318. * specific language governing permissions and limitations
  70319. * under the License.
  70320. */
  70321. var Rect$2 = Rect;
  70322. var linearMap$1 = linearMap;
  70323. var asc$2 = asc;
  70324. var bind$4 = bind;
  70325. var each$23 = each$1;
  70326. // Constants
  70327. var DEFAULT_LOCATION_EDGE_GAP = 7;
  70328. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  70329. var DEFAULT_FILLER_SIZE = 30;
  70330. var HORIZONTAL = 'horizontal';
  70331. var VERTICAL = 'vertical';
  70332. var LABEL_GAP = 5;
  70333. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  70334. var SliderZoomView = DataZoomView.extend({
  70335. type: 'dataZoom.slider',
  70336. init: function (ecModel, api) {
  70337. /**
  70338. * @private
  70339. * @type {Object}
  70340. */
  70341. this._displayables = {};
  70342. /**
  70343. * @private
  70344. * @type {string}
  70345. */
  70346. this._orient;
  70347. /**
  70348. * [0, 100]
  70349. * @private
  70350. */
  70351. this._range;
  70352. /**
  70353. * [coord of the first handle, coord of the second handle]
  70354. * @private
  70355. */
  70356. this._handleEnds;
  70357. /**
  70358. * [length, thick]
  70359. * @private
  70360. * @type {Array.<number>}
  70361. */
  70362. this._size;
  70363. /**
  70364. * @private
  70365. * @type {number}
  70366. */
  70367. this._handleWidth;
  70368. /**
  70369. * @private
  70370. * @type {number}
  70371. */
  70372. this._handleHeight;
  70373. /**
  70374. * @private
  70375. */
  70376. this._location;
  70377. /**
  70378. * @private
  70379. */
  70380. this._dragging;
  70381. /**
  70382. * @private
  70383. */
  70384. this._dataShadowInfo;
  70385. this.api = api;
  70386. },
  70387. /**
  70388. * @override
  70389. */
  70390. render: function (dataZoomModel, ecModel, api, payload) {
  70391. SliderZoomView.superApply(this, 'render', arguments);
  70392. createOrUpdate(
  70393. this,
  70394. '_dispatchZoomAction',
  70395. this.dataZoomModel.get('throttle'),
  70396. 'fixRate'
  70397. );
  70398. this._orient = dataZoomModel.get('orient');
  70399. if (this.dataZoomModel.get('show') === false) {
  70400. this.group.removeAll();
  70401. return;
  70402. }
  70403. // Notice: this._resetInterval() should not be executed when payload.type
  70404. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  70405. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  70406. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  70407. this._buildView();
  70408. }
  70409. this._updateView();
  70410. },
  70411. /**
  70412. * @override
  70413. */
  70414. remove: function () {
  70415. SliderZoomView.superApply(this, 'remove', arguments);
  70416. clear(this, '_dispatchZoomAction');
  70417. },
  70418. /**
  70419. * @override
  70420. */
  70421. dispose: function () {
  70422. SliderZoomView.superApply(this, 'dispose', arguments);
  70423. clear(this, '_dispatchZoomAction');
  70424. },
  70425. _buildView: function () {
  70426. var thisGroup = this.group;
  70427. thisGroup.removeAll();
  70428. this._resetLocation();
  70429. this._resetInterval();
  70430. var barGroup = this._displayables.barGroup = new Group();
  70431. this._renderBackground();
  70432. this._renderHandle();
  70433. this._renderDataShadow();
  70434. thisGroup.add(barGroup);
  70435. this._positionGroup();
  70436. },
  70437. /**
  70438. * @private
  70439. */
  70440. _resetLocation: function () {
  70441. var dataZoomModel = this.dataZoomModel;
  70442. var api = this.api;
  70443. // If some of x/y/width/height are not specified,
  70444. // auto-adapt according to target grid.
  70445. var coordRect = this._findCoordRect();
  70446. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  70447. // Default align by coordinate system rect.
  70448. var positionInfo = this._orient === HORIZONTAL
  70449. ? {
  70450. // Why using 'right', because right should be used in vertical,
  70451. // and it is better to be consistent for dealing with position param merge.
  70452. right: ecSize.width - coordRect.x - coordRect.width,
  70453. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  70454. width: coordRect.width,
  70455. height: DEFAULT_FILLER_SIZE
  70456. }
  70457. : { // vertical
  70458. right: DEFAULT_LOCATION_EDGE_GAP,
  70459. top: coordRect.y,
  70460. width: DEFAULT_FILLER_SIZE,
  70461. height: coordRect.height
  70462. };
  70463. // Do not write back to option and replace value 'ph', because
  70464. // the 'ph' value should be recalculated when resize.
  70465. var layoutParams = getLayoutParams(dataZoomModel.option);
  70466. // Replace the placeholder value.
  70467. each$1(['right', 'top', 'width', 'height'], function (name) {
  70468. if (layoutParams[name] === 'ph') {
  70469. layoutParams[name] = positionInfo[name];
  70470. }
  70471. });
  70472. var layoutRect = getLayoutRect(
  70473. layoutParams,
  70474. ecSize,
  70475. dataZoomModel.padding
  70476. );
  70477. this._location = {x: layoutRect.x, y: layoutRect.y};
  70478. this._size = [layoutRect.width, layoutRect.height];
  70479. this._orient === VERTICAL && this._size.reverse();
  70480. },
  70481. /**
  70482. * @private
  70483. */
  70484. _positionGroup: function () {
  70485. var thisGroup = this.group;
  70486. var location = this._location;
  70487. var orient = this._orient;
  70488. // Just use the first axis to determine mapping.
  70489. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  70490. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  70491. var barGroup = this._displayables.barGroup;
  70492. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  70493. // Transform barGroup.
  70494. barGroup.attr(
  70495. (orient === HORIZONTAL && !inverse)
  70496. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  70497. : (orient === HORIZONTAL && inverse)
  70498. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  70499. : (orient === VERTICAL && !inverse)
  70500. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  70501. // Dont use Math.PI, considering shadow direction.
  70502. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  70503. );
  70504. // Position barGroup
  70505. var rect = thisGroup.getBoundingRect([barGroup]);
  70506. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  70507. },
  70508. /**
  70509. * @private
  70510. */
  70511. _getViewExtent: function () {
  70512. return [0, this._size[0]];
  70513. },
  70514. _renderBackground: function () {
  70515. var dataZoomModel = this.dataZoomModel;
  70516. var size = this._size;
  70517. var barGroup = this._displayables.barGroup;
  70518. barGroup.add(new Rect$2({
  70519. silent: true,
  70520. shape: {
  70521. x: 0, y: 0, width: size[0], height: size[1]
  70522. },
  70523. style: {
  70524. fill: dataZoomModel.get('backgroundColor')
  70525. },
  70526. z2: -40
  70527. }));
  70528. // Click panel, over shadow, below handles.
  70529. barGroup.add(new Rect$2({
  70530. shape: {
  70531. x: 0, y: 0, width: size[0], height: size[1]
  70532. },
  70533. style: {
  70534. fill: 'transparent'
  70535. },
  70536. z2: 0,
  70537. onclick: bind(this._onClickPanelClick, this)
  70538. }));
  70539. },
  70540. _renderDataShadow: function () {
  70541. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  70542. if (!info) {
  70543. return;
  70544. }
  70545. var size = this._size;
  70546. var seriesModel = info.series;
  70547. var data = seriesModel.getRawData();
  70548. var otherDim = seriesModel.getShadowDim
  70549. ? seriesModel.getShadowDim() // @see candlestick
  70550. : info.otherDim;
  70551. if (otherDim == null) {
  70552. return;
  70553. }
  70554. var otherDataExtent = data.getDataExtent(otherDim);
  70555. // Nice extent.
  70556. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  70557. otherDataExtent = [
  70558. otherDataExtent[0] - otherOffset,
  70559. otherDataExtent[1] + otherOffset
  70560. ];
  70561. var otherShadowExtent = [0, size[1]];
  70562. var thisShadowExtent = [0, size[0]];
  70563. var areaPoints = [[size[0], 0], [0, 0]];
  70564. var linePoints = [];
  70565. var step = thisShadowExtent[1] / (data.count() - 1);
  70566. var thisCoord = 0;
  70567. // Optimize for large data shadow
  70568. var stride = Math.round(data.count() / size[0]);
  70569. var lastIsEmpty;
  70570. data.each([otherDim], function (value, index) {
  70571. if (stride > 0 && (index % stride)) {
  70572. thisCoord += step;
  70573. return;
  70574. }
  70575. // FIXME
  70576. // Should consider axis.min/axis.max when drawing dataShadow.
  70577. // FIXME
  70578. // 应该使用统一的空判断?还是在list里进行空判断?
  70579. var isEmpty = value == null || isNaN(value) || value === '';
  70580. // See #4235.
  70581. var otherCoord = isEmpty
  70582. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  70583. // Attempt to draw data shadow precisely when there are empty value.
  70584. if (isEmpty && !lastIsEmpty && index) {
  70585. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  70586. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  70587. }
  70588. else if (!isEmpty && lastIsEmpty) {
  70589. areaPoints.push([thisCoord, 0]);
  70590. linePoints.push([thisCoord, 0]);
  70591. }
  70592. areaPoints.push([thisCoord, otherCoord]);
  70593. linePoints.push([thisCoord, otherCoord]);
  70594. thisCoord += step;
  70595. lastIsEmpty = isEmpty;
  70596. });
  70597. var dataZoomModel = this.dataZoomModel;
  70598. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  70599. this._displayables.barGroup.add(new Polygon({
  70600. shape: {points: areaPoints},
  70601. style: defaults(
  70602. {fill: dataZoomModel.get('dataBackgroundColor')},
  70603. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  70604. ),
  70605. silent: true,
  70606. z2: -20
  70607. }));
  70608. this._displayables.barGroup.add(new Polyline({
  70609. shape: {points: linePoints},
  70610. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  70611. silent: true,
  70612. z2: -19
  70613. }));
  70614. },
  70615. _prepareDataShadowInfo: function () {
  70616. var dataZoomModel = this.dataZoomModel;
  70617. var showDataShadow = dataZoomModel.get('showDataShadow');
  70618. if (showDataShadow === false) {
  70619. return;
  70620. }
  70621. // Find a representative series.
  70622. var result;
  70623. var ecModel = this.ecModel;
  70624. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  70625. var seriesModels = dataZoomModel
  70626. .getAxisProxy(dimNames.name, axisIndex)
  70627. .getTargetSeriesModels();
  70628. each$1(seriesModels, function (seriesModel) {
  70629. if (result) {
  70630. return;
  70631. }
  70632. if (showDataShadow !== true && indexOf(
  70633. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  70634. ) < 0
  70635. ) {
  70636. return;
  70637. }
  70638. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  70639. var otherDim = getOtherDim(dimNames.name);
  70640. var otherAxisInverse;
  70641. var coordSys = seriesModel.coordinateSystem;
  70642. if (otherDim != null && coordSys.getOtherAxis) {
  70643. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  70644. }
  70645. otherDim = seriesModel.getData().mapDimension(otherDim);
  70646. result = {
  70647. thisAxis: thisAxis,
  70648. series: seriesModel,
  70649. thisDim: dimNames.name,
  70650. otherDim: otherDim,
  70651. otherAxisInverse: otherAxisInverse
  70652. };
  70653. }, this);
  70654. }, this);
  70655. return result;
  70656. },
  70657. _renderHandle: function () {
  70658. var displaybles = this._displayables;
  70659. var handles = displaybles.handles = [];
  70660. var handleLabels = displaybles.handleLabels = [];
  70661. var barGroup = this._displayables.barGroup;
  70662. var size = this._size;
  70663. var dataZoomModel = this.dataZoomModel;
  70664. barGroup.add(displaybles.filler = new Rect$2({
  70665. draggable: true,
  70666. cursor: getCursor(this._orient),
  70667. drift: bind$4(this._onDragMove, this, 'all'),
  70668. onmousemove: function (e) {
  70669. // Fot mobile devicem, prevent screen slider on the button.
  70670. stop(e.event);
  70671. },
  70672. ondragstart: bind$4(this._showDataInfo, this, true),
  70673. ondragend: bind$4(this._onDragEnd, this),
  70674. onmouseover: bind$4(this._showDataInfo, this, true),
  70675. onmouseout: bind$4(this._showDataInfo, this, false),
  70676. style: {
  70677. fill: dataZoomModel.get('fillerColor'),
  70678. textPosition: 'inside'
  70679. }
  70680. }));
  70681. // Frame border.
  70682. barGroup.add(new Rect$2(subPixelOptimizeRect({
  70683. silent: true,
  70684. shape: {
  70685. x: 0,
  70686. y: 0,
  70687. width: size[0],
  70688. height: size[1]
  70689. },
  70690. style: {
  70691. stroke: dataZoomModel.get('dataBackgroundColor')
  70692. || dataZoomModel.get('borderColor'),
  70693. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  70694. fill: 'rgba(0,0,0,0)'
  70695. }
  70696. })));
  70697. each$23([0, 1], function (handleIndex) {
  70698. var path = createIcon(
  70699. dataZoomModel.get('handleIcon'),
  70700. {
  70701. cursor: getCursor(this._orient),
  70702. draggable: true,
  70703. drift: bind$4(this._onDragMove, this, handleIndex),
  70704. onmousemove: function (e) {
  70705. // Fot mobile devicem, prevent screen slider on the button.
  70706. stop(e.event);
  70707. },
  70708. ondragend: bind$4(this._onDragEnd, this),
  70709. onmouseover: bind$4(this._showDataInfo, this, true),
  70710. onmouseout: bind$4(this._showDataInfo, this, false)
  70711. },
  70712. {x: -1, y: 0, width: 2, height: 2}
  70713. );
  70714. var bRect = path.getBoundingRect();
  70715. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  70716. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  70717. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  70718. var handleColor = dataZoomModel.get('handleColor');
  70719. // Compatitable with previous version
  70720. if (handleColor != null) {
  70721. path.style.fill = handleColor;
  70722. }
  70723. barGroup.add(handles[handleIndex] = path);
  70724. var textStyleModel = dataZoomModel.textStyleModel;
  70725. this.group.add(
  70726. handleLabels[handleIndex] = new Text({
  70727. silent: true,
  70728. invisible: true,
  70729. style: {
  70730. x: 0, y: 0, text: '',
  70731. textVerticalAlign: 'middle',
  70732. textAlign: 'center',
  70733. textFill: textStyleModel.getTextColor(),
  70734. textFont: textStyleModel.getFont()
  70735. },
  70736. z2: 10
  70737. }));
  70738. }, this);
  70739. },
  70740. /**
  70741. * @private
  70742. */
  70743. _resetInterval: function () {
  70744. var range = this._range = this.dataZoomModel.getPercentRange();
  70745. var viewExtent = this._getViewExtent();
  70746. this._handleEnds = [
  70747. linearMap$1(range[0], [0, 100], viewExtent, true),
  70748. linearMap$1(range[1], [0, 100], viewExtent, true)
  70749. ];
  70750. },
  70751. /**
  70752. * @private
  70753. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  70754. * @param {number} delta
  70755. * @return {boolean} changed
  70756. */
  70757. _updateInterval: function (handleIndex, delta) {
  70758. var dataZoomModel = this.dataZoomModel;
  70759. var handleEnds = this._handleEnds;
  70760. var viewExtend = this._getViewExtent();
  70761. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  70762. var percentExtent = [0, 100];
  70763. sliderMove(
  70764. delta,
  70765. handleEnds,
  70766. viewExtend,
  70767. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  70768. minMaxSpan.minSpan != null
  70769. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  70770. minMaxSpan.maxSpan != null
  70771. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  70772. );
  70773. var lastRange = this._range;
  70774. var range = this._range = asc$2([
  70775. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  70776. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  70777. ]);
  70778. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  70779. },
  70780. /**
  70781. * @private
  70782. */
  70783. _updateView: function (nonRealtime) {
  70784. var displaybles = this._displayables;
  70785. var handleEnds = this._handleEnds;
  70786. var handleInterval = asc$2(handleEnds.slice());
  70787. var size = this._size;
  70788. each$23([0, 1], function (handleIndex) {
  70789. // Handles
  70790. var handle = displaybles.handles[handleIndex];
  70791. var handleHeight = this._handleHeight;
  70792. handle.attr({
  70793. scale: [handleHeight / 2, handleHeight / 2],
  70794. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  70795. });
  70796. }, this);
  70797. // Filler
  70798. displaybles.filler.setShape({
  70799. x: handleInterval[0],
  70800. y: 0,
  70801. width: handleInterval[1] - handleInterval[0],
  70802. height: size[1]
  70803. });
  70804. this._updateDataInfo(nonRealtime);
  70805. },
  70806. /**
  70807. * @private
  70808. */
  70809. _updateDataInfo: function (nonRealtime) {
  70810. var dataZoomModel = this.dataZoomModel;
  70811. var displaybles = this._displayables;
  70812. var handleLabels = displaybles.handleLabels;
  70813. var orient = this._orient;
  70814. var labelTexts = ['', ''];
  70815. // FIXME
  70816. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  70817. if (dataZoomModel.get('showDetail')) {
  70818. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  70819. if (axisProxy) {
  70820. var axis = axisProxy.getAxisModel().axis;
  70821. var range = this._range;
  70822. var dataInterval = nonRealtime
  70823. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  70824. ? axisProxy.calculateDataWindow({
  70825. start: range[0], end: range[1]
  70826. }).valueWindow
  70827. : axisProxy.getDataValueWindow();
  70828. labelTexts = [
  70829. this._formatLabel(dataInterval[0], axis),
  70830. this._formatLabel(dataInterval[1], axis)
  70831. ];
  70832. }
  70833. }
  70834. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  70835. setLabel.call(this, 0);
  70836. setLabel.call(this, 1);
  70837. function setLabel(handleIndex) {
  70838. // Label
  70839. // Text should not transform by barGroup.
  70840. // Ignore handlers transform
  70841. var barTransform = getTransform(
  70842. displaybles.handles[handleIndex].parent, this.group
  70843. );
  70844. var direction = transformDirection(
  70845. handleIndex === 0 ? 'right' : 'left', barTransform
  70846. );
  70847. var offset = this._handleWidth / 2 + LABEL_GAP;
  70848. var textPoint = applyTransform$1(
  70849. [
  70850. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  70851. this._size[1] / 2
  70852. ],
  70853. barTransform
  70854. );
  70855. handleLabels[handleIndex].setStyle({
  70856. x: textPoint[0],
  70857. y: textPoint[1],
  70858. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  70859. textAlign: orient === HORIZONTAL ? direction : 'center',
  70860. text: labelTexts[handleIndex]
  70861. });
  70862. }
  70863. },
  70864. /**
  70865. * @private
  70866. */
  70867. _formatLabel: function (value, axis) {
  70868. var dataZoomModel = this.dataZoomModel;
  70869. var labelFormatter = dataZoomModel.get('labelFormatter');
  70870. var labelPrecision = dataZoomModel.get('labelPrecision');
  70871. if (labelPrecision == null || labelPrecision === 'auto') {
  70872. labelPrecision = axis.getPixelPrecision();
  70873. }
  70874. var valueStr = (value == null || isNaN(value))
  70875. ? ''
  70876. // FIXME Glue code
  70877. : (axis.type === 'category' || axis.type === 'time')
  70878. ? axis.scale.getLabel(Math.round(value))
  70879. // param of toFixed should less then 20.
  70880. : value.toFixed(Math.min(labelPrecision, 20));
  70881. return isFunction$1(labelFormatter)
  70882. ? labelFormatter(value, valueStr)
  70883. : isString(labelFormatter)
  70884. ? labelFormatter.replace('{value}', valueStr)
  70885. : valueStr;
  70886. },
  70887. /**
  70888. * @private
  70889. * @param {boolean} showOrHide true: show, false: hide
  70890. */
  70891. _showDataInfo: function (showOrHide) {
  70892. // Always show when drgging.
  70893. showOrHide = this._dragging || showOrHide;
  70894. var handleLabels = this._displayables.handleLabels;
  70895. handleLabels[0].attr('invisible', !showOrHide);
  70896. handleLabels[1].attr('invisible', !showOrHide);
  70897. },
  70898. _onDragMove: function (handleIndex, dx, dy) {
  70899. this._dragging = true;
  70900. // Transform dx, dy to bar coordination.
  70901. var barTransform = this._displayables.barGroup.getLocalTransform();
  70902. var vertex = applyTransform$1([dx, dy], barTransform, true);
  70903. var changed = this._updateInterval(handleIndex, vertex[0]);
  70904. var realtime = this.dataZoomModel.get('realtime');
  70905. this._updateView(!realtime);
  70906. // Avoid dispatch dataZoom repeatly but range not changed,
  70907. // which cause bad visual effect when progressive enabled.
  70908. changed && realtime && this._dispatchZoomAction();
  70909. },
  70910. _onDragEnd: function () {
  70911. this._dragging = false;
  70912. this._showDataInfo(false);
  70913. // While in realtime mode and stream mode, dispatch action when
  70914. // drag end will cause the whole view rerender, which is unnecessary.
  70915. var realtime = this.dataZoomModel.get('realtime');
  70916. !realtime && this._dispatchZoomAction();
  70917. },
  70918. _onClickPanelClick: function (e) {
  70919. var size = this._size;
  70920. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  70921. if (localPoint[0] < 0 || localPoint[0] > size[0]
  70922. || localPoint[1] < 0 || localPoint[1] > size[1]
  70923. ) {
  70924. return;
  70925. }
  70926. var handleEnds = this._handleEnds;
  70927. var center = (handleEnds[0] + handleEnds[1]) / 2;
  70928. var changed = this._updateInterval('all', localPoint[0] - center);
  70929. this._updateView();
  70930. changed && this._dispatchZoomAction();
  70931. },
  70932. /**
  70933. * This action will be throttled.
  70934. * @private
  70935. */
  70936. _dispatchZoomAction: function () {
  70937. var range = this._range;
  70938. this.api.dispatchAction({
  70939. type: 'dataZoom',
  70940. from: this.uid,
  70941. dataZoomId: this.dataZoomModel.id,
  70942. start: range[0],
  70943. end: range[1]
  70944. });
  70945. },
  70946. /**
  70947. * @private
  70948. */
  70949. _findCoordRect: function () {
  70950. // Find the grid coresponding to the first axis referred by dataZoom.
  70951. var rect;
  70952. each$23(this.getTargetCoordInfo(), function (coordInfoList) {
  70953. if (!rect && coordInfoList.length) {
  70954. var coordSys = coordInfoList[0].model.coordinateSystem;
  70955. rect = coordSys.getRect && coordSys.getRect();
  70956. }
  70957. });
  70958. if (!rect) {
  70959. var width = this.api.getWidth();
  70960. var height = this.api.getHeight();
  70961. rect = {
  70962. x: width * 0.2,
  70963. y: height * 0.2,
  70964. width: width * 0.6,
  70965. height: height * 0.6
  70966. };
  70967. }
  70968. return rect;
  70969. }
  70970. });
  70971. function getOtherDim(thisDim) {
  70972. // FIXME
  70973. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  70974. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  70975. return map$$1[thisDim];
  70976. }
  70977. function getCursor(orient) {
  70978. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  70979. }
  70980. /*
  70981. * Licensed to the Apache Software Foundation (ASF) under one
  70982. * or more contributor license agreements. See the NOTICE file
  70983. * distributed with this work for additional information
  70984. * regarding copyright ownership. The ASF licenses this file
  70985. * to you under the Apache License, Version 2.0 (the
  70986. * "License"); you may not use this file except in compliance
  70987. * with the License. You may obtain a copy of the License at
  70988. *
  70989. * http://www.apache.org/licenses/LICENSE-2.0
  70990. *
  70991. * Unless required by applicable law or agreed to in writing,
  70992. * software distributed under the License is distributed on an
  70993. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70994. * KIND, either express or implied. See the License for the
  70995. * specific language governing permissions and limitations
  70996. * under the License.
  70997. */
  70998. DataZoomModel.extend({
  70999. type: 'dataZoom.inside',
  71000. /**
  71001. * @protected
  71002. */
  71003. defaultOption: {
  71004. disabled: false, // Whether disable this inside zoom.
  71005. zoomLock: false, // Whether disable zoom but only pan.
  71006. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  71007. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  71008. moveOnMouseWheel: false, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  71009. preventDefaultMouseMove: true
  71010. }
  71011. });
  71012. /*
  71013. * Licensed to the Apache Software Foundation (ASF) under one
  71014. * or more contributor license agreements. See the NOTICE file
  71015. * distributed with this work for additional information
  71016. * regarding copyright ownership. The ASF licenses this file
  71017. * to you under the Apache License, Version 2.0 (the
  71018. * "License"); you may not use this file except in compliance
  71019. * with the License. You may obtain a copy of the License at
  71020. *
  71021. * http://www.apache.org/licenses/LICENSE-2.0
  71022. *
  71023. * Unless required by applicable law or agreed to in writing,
  71024. * software distributed under the License is distributed on an
  71025. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71026. * KIND, either express or implied. See the License for the
  71027. * specific language governing permissions and limitations
  71028. * under the License.
  71029. */
  71030. // Only create one roam controller for each coordinate system.
  71031. // one roam controller might be refered by two inside data zoom
  71032. // components (for example, one for x and one for y). When user
  71033. // pan or zoom, only dispatch one action for those data zoom
  71034. // components.
  71035. var ATTR$1 = '\0_ec_dataZoom_roams';
  71036. /**
  71037. * @public
  71038. * @param {module:echarts/ExtensionAPI} api
  71039. * @param {Object} dataZoomInfo
  71040. * @param {string} dataZoomInfo.coordId
  71041. * @param {Function} dataZoomInfo.containsPoint
  71042. * @param {Array.<string>} dataZoomInfo.allCoordIds
  71043. * @param {string} dataZoomInfo.dataZoomId
  71044. * @param {Object} dataZoomInfo.getRange
  71045. * @param {Function} dataZoomInfo.getRange.pan
  71046. * @param {Function} dataZoomInfo.getRange.zoom
  71047. * @param {Function} dataZoomInfo.getRange.scrollMove
  71048. * @param {boolean} dataZoomInfo.dataZoomModel
  71049. */
  71050. function register$2(api, dataZoomInfo) {
  71051. var store = giveStore(api);
  71052. var theDataZoomId = dataZoomInfo.dataZoomId;
  71053. var theCoordId = dataZoomInfo.coordId;
  71054. // Do clean when a dataZoom changes its target coordnate system.
  71055. // Avoid memory leak, dispose all not-used-registered.
  71056. each$1(store, function (record, coordId) {
  71057. var dataZoomInfos = record.dataZoomInfos;
  71058. if (dataZoomInfos[theDataZoomId]
  71059. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  71060. ) {
  71061. delete dataZoomInfos[theDataZoomId];
  71062. record.count--;
  71063. }
  71064. });
  71065. cleanStore(store);
  71066. var record = store[theCoordId];
  71067. // Create if needed.
  71068. if (!record) {
  71069. record = store[theCoordId] = {
  71070. coordId: theCoordId,
  71071. dataZoomInfos: {},
  71072. count: 0
  71073. };
  71074. record.controller = createController(api, record);
  71075. record.dispatchAction = curry(dispatchAction$1, api);
  71076. }
  71077. // Update reference of dataZoom.
  71078. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  71079. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  71080. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  71081. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  71082. // Consider resize, area should be always updated.
  71083. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  71084. // Update throttle.
  71085. createOrUpdate(
  71086. record,
  71087. 'dispatchAction',
  71088. dataZoomInfo.dataZoomModel.get('throttle', true),
  71089. 'fixRate'
  71090. );
  71091. }
  71092. /**
  71093. * @public
  71094. * @param {module:echarts/ExtensionAPI} api
  71095. * @param {string} dataZoomId
  71096. */
  71097. function unregister$1(api, dataZoomId) {
  71098. var store = giveStore(api);
  71099. each$1(store, function (record) {
  71100. record.controller.dispose();
  71101. var dataZoomInfos = record.dataZoomInfos;
  71102. if (dataZoomInfos[dataZoomId]) {
  71103. delete dataZoomInfos[dataZoomId];
  71104. record.count--;
  71105. }
  71106. });
  71107. cleanStore(store);
  71108. }
  71109. /**
  71110. * @public
  71111. */
  71112. function generateCoordId(coordModel) {
  71113. return coordModel.type + '\0_' + coordModel.id;
  71114. }
  71115. /**
  71116. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  71117. * @type {Array.<Object>}
  71118. */
  71119. function giveStore(api) {
  71120. // Mount store on zrender instance, so that we do not
  71121. // need to worry about dispose.
  71122. var zr = api.getZr();
  71123. return zr[ATTR$1] || (zr[ATTR$1] = {});
  71124. }
  71125. function createController(api, newRecord) {
  71126. var controller = new RoamController(api.getZr());
  71127. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  71128. controller.on(eventName, function (event) {
  71129. var batch = [];
  71130. each$1(newRecord.dataZoomInfos, function (info) {
  71131. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  71132. // moveOnMouseWheel, ...) enabled.
  71133. if (!event.isAvailableBehavior(info.dataZoomModel.option)) {
  71134. return;
  71135. }
  71136. var method = (info.getRange || {})[eventName];
  71137. var range = method && method(newRecord.controller, event);
  71138. !info.dataZoomModel.get('disabled', true) && range && batch.push({
  71139. dataZoomId: info.dataZoomId,
  71140. start: range[0],
  71141. end: range[1]
  71142. });
  71143. });
  71144. batch.length && newRecord.dispatchAction(batch);
  71145. });
  71146. });
  71147. return controller;
  71148. }
  71149. function cleanStore(store) {
  71150. each$1(store, function (record, coordId) {
  71151. if (!record.count) {
  71152. record.controller.dispose();
  71153. delete store[coordId];
  71154. }
  71155. });
  71156. }
  71157. /**
  71158. * This action will be throttled.
  71159. */
  71160. function dispatchAction$1(api, batch) {
  71161. api.dispatchAction({
  71162. type: 'dataZoom',
  71163. batch: batch
  71164. });
  71165. }
  71166. /**
  71167. * Merge roamController settings when multiple dataZooms share one roamController.
  71168. */
  71169. function mergeControllerParams(dataZoomInfos) {
  71170. var controlType;
  71171. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  71172. // as string, it is probably revert to reserved word by compress tool. See #7411.
  71173. var prefix = 'type_';
  71174. var typePriority = {
  71175. 'type_true': 2,
  71176. 'type_move': 1,
  71177. 'type_false': 0,
  71178. 'type_undefined': -1
  71179. };
  71180. var preventDefaultMouseMove = true;
  71181. each$1(dataZoomInfos, function (dataZoomInfo) {
  71182. var dataZoomModel = dataZoomInfo.dataZoomModel;
  71183. var oneType = dataZoomModel.get('disabled', true)
  71184. ? false
  71185. : dataZoomModel.get('zoomLock', true)
  71186. ? 'move'
  71187. : true;
  71188. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  71189. controlType = oneType;
  71190. }
  71191. // Prevent default move event by default. If one false, do not prevent. Otherwise
  71192. // users may be confused why it does not work when multiple insideZooms exist.
  71193. preventDefaultMouseMove &= dataZoomModel.get('preventDefaultMouseMove', true);
  71194. });
  71195. return {
  71196. controlType: controlType,
  71197. opt: {
  71198. // RoamController will enable all of these functionalities,
  71199. // and the final behavior is determined by its event listener
  71200. // provided by each inside zoom.
  71201. zoomOnMouseWheel: true,
  71202. moveOnMouseMove: true,
  71203. moveOnMouseWheel: true,
  71204. preventDefaultMouseMove: !!preventDefaultMouseMove
  71205. }
  71206. };
  71207. }
  71208. /*
  71209. * Licensed to the Apache Software Foundation (ASF) under one
  71210. * or more contributor license agreements. See the NOTICE file
  71211. * distributed with this work for additional information
  71212. * regarding copyright ownership. The ASF licenses this file
  71213. * to you under the Apache License, Version 2.0 (the
  71214. * "License"); you may not use this file except in compliance
  71215. * with the License. You may obtain a copy of the License at
  71216. *
  71217. * http://www.apache.org/licenses/LICENSE-2.0
  71218. *
  71219. * Unless required by applicable law or agreed to in writing,
  71220. * software distributed under the License is distributed on an
  71221. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71222. * KIND, either express or implied. See the License for the
  71223. * specific language governing permissions and limitations
  71224. * under the License.
  71225. */
  71226. var bind$5 = bind;
  71227. var InsideZoomView = DataZoomView.extend({
  71228. type: 'dataZoom.inside',
  71229. /**
  71230. * @override
  71231. */
  71232. init: function (ecModel, api) {
  71233. /**
  71234. * 'throttle' is used in this.dispatchAction, so we save range
  71235. * to avoid missing some 'pan' info.
  71236. * @private
  71237. * @type {Array.<number>}
  71238. */
  71239. this._range;
  71240. },
  71241. /**
  71242. * @override
  71243. */
  71244. render: function (dataZoomModel, ecModel, api, payload) {
  71245. InsideZoomView.superApply(this, 'render', arguments);
  71246. // Hance the `throttle` util ensures to preserve command order,
  71247. // here simply updating range all the time will not cause missing
  71248. // any of the the roam change.
  71249. this._range = dataZoomModel.getPercentRange();
  71250. // Reset controllers.
  71251. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  71252. var allCoordIds = map(coordInfoList, function (coordInfo) {
  71253. return generateCoordId(coordInfo.model);
  71254. });
  71255. each$1(coordInfoList, function (coordInfo) {
  71256. var coordModel = coordInfo.model;
  71257. var getRange = {};
  71258. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  71259. getRange[eventName] = bind$5(roamHandlers[eventName], this, coordInfo, coordSysName);
  71260. }, this);
  71261. register$2(
  71262. api,
  71263. {
  71264. coordId: generateCoordId(coordModel),
  71265. allCoordIds: allCoordIds,
  71266. containsPoint: function (e, x, y) {
  71267. return coordModel.coordinateSystem.containPoint([x, y]);
  71268. },
  71269. dataZoomId: dataZoomModel.id,
  71270. dataZoomModel: dataZoomModel,
  71271. getRange: getRange
  71272. }
  71273. );
  71274. }, this);
  71275. }, this);
  71276. },
  71277. /**
  71278. * @override
  71279. */
  71280. dispose: function () {
  71281. unregister$1(this.api, this.dataZoomModel.id);
  71282. InsideZoomView.superApply(this, 'dispose', arguments);
  71283. this._range = null;
  71284. }
  71285. });
  71286. var roamHandlers = {
  71287. /**
  71288. * @this {module:echarts/component/dataZoom/InsideZoomView}
  71289. */
  71290. zoom: function (coordInfo, coordSysName, controller, e) {
  71291. var lastRange = this._range;
  71292. var range = lastRange.slice();
  71293. // Calculate transform by the first axis.
  71294. var axisModel = coordInfo.axisModels[0];
  71295. if (!axisModel) {
  71296. return;
  71297. }
  71298. var directionInfo = getDirectionInfo[coordSysName](
  71299. null, [e.originX, e.originY], axisModel, controller, coordInfo
  71300. );
  71301. var percentPoint = (
  71302. directionInfo.signal > 0
  71303. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  71304. : (directionInfo.pixel - directionInfo.pixelStart)
  71305. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  71306. var scale = Math.max(1 / e.scale, 0);
  71307. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  71308. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  71309. // Restrict range.
  71310. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  71311. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  71312. this._range = range;
  71313. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  71314. return range;
  71315. }
  71316. },
  71317. /**
  71318. * @this {module:echarts/component/dataZoom/InsideZoomView}
  71319. */
  71320. pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  71321. var directionInfo = getDirectionInfo[coordSysName](
  71322. [e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo
  71323. );
  71324. return directionInfo.signal
  71325. * (range[1] - range[0])
  71326. * directionInfo.pixel / directionInfo.pixelLength;
  71327. }),
  71328. /**
  71329. * @this {module:echarts/component/dataZoom/InsideZoomView}
  71330. */
  71331. scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  71332. var directionInfo = getDirectionInfo[coordSysName](
  71333. [0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo
  71334. );
  71335. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  71336. })
  71337. };
  71338. function makeMover(getPercentDelta) {
  71339. return function (coordInfo, coordSysName, controller, e) {
  71340. var lastRange = this._range;
  71341. var range = lastRange.slice();
  71342. // Calculate transform by the first axis.
  71343. var axisModel = coordInfo.axisModels[0];
  71344. if (!axisModel) {
  71345. return;
  71346. }
  71347. var percentDelta = getPercentDelta(
  71348. range, axisModel, coordInfo, coordSysName, controller, e
  71349. );
  71350. sliderMove(percentDelta, range, [0, 100], 'all');
  71351. this._range = range;
  71352. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  71353. return range;
  71354. }
  71355. };
  71356. }
  71357. var getDirectionInfo = {
  71358. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  71359. var axis = axisModel.axis;
  71360. var ret = {};
  71361. var rect = coordInfo.model.coordinateSystem.getRect();
  71362. oldPoint = oldPoint || [0, 0];
  71363. if (axis.dim === 'x') {
  71364. ret.pixel = newPoint[0] - oldPoint[0];
  71365. ret.pixelLength = rect.width;
  71366. ret.pixelStart = rect.x;
  71367. ret.signal = axis.inverse ? 1 : -1;
  71368. }
  71369. else { // axis.dim === 'y'
  71370. ret.pixel = newPoint[1] - oldPoint[1];
  71371. ret.pixelLength = rect.height;
  71372. ret.pixelStart = rect.y;
  71373. ret.signal = axis.inverse ? -1 : 1;
  71374. }
  71375. return ret;
  71376. },
  71377. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  71378. var axis = axisModel.axis;
  71379. var ret = {};
  71380. var polar = coordInfo.model.coordinateSystem;
  71381. var radiusExtent = polar.getRadiusAxis().getExtent();
  71382. var angleExtent = polar.getAngleAxis().getExtent();
  71383. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  71384. newPoint = polar.pointToCoord(newPoint);
  71385. if (axisModel.mainType === 'radiusAxis') {
  71386. ret.pixel = newPoint[0] - oldPoint[0];
  71387. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  71388. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  71389. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  71390. ret.pixelStart = radiusExtent[0];
  71391. ret.signal = axis.inverse ? 1 : -1;
  71392. }
  71393. else { // 'angleAxis'
  71394. ret.pixel = newPoint[1] - oldPoint[1];
  71395. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  71396. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  71397. ret.pixelLength = angleExtent[1] - angleExtent[0];
  71398. ret.pixelStart = angleExtent[0];
  71399. ret.signal = axis.inverse ? -1 : 1;
  71400. }
  71401. return ret;
  71402. },
  71403. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  71404. var axis = axisModel.axis;
  71405. var rect = coordInfo.model.coordinateSystem.getRect();
  71406. var ret = {};
  71407. oldPoint = oldPoint || [0, 0];
  71408. if (axis.orient === 'horizontal') {
  71409. ret.pixel = newPoint[0] - oldPoint[0];
  71410. ret.pixelLength = rect.width;
  71411. ret.pixelStart = rect.x;
  71412. ret.signal = axis.inverse ? 1 : -1;
  71413. }
  71414. else { // 'vertical'
  71415. ret.pixel = newPoint[1] - oldPoint[1];
  71416. ret.pixelLength = rect.height;
  71417. ret.pixelStart = rect.y;
  71418. ret.signal = axis.inverse ? -1 : 1;
  71419. }
  71420. return ret;
  71421. }
  71422. };
  71423. /*
  71424. * Licensed to the Apache Software Foundation (ASF) under one
  71425. * or more contributor license agreements. See the NOTICE file
  71426. * distributed with this work for additional information
  71427. * regarding copyright ownership. The ASF licenses this file
  71428. * to you under the Apache License, Version 2.0 (the
  71429. * "License"); you may not use this file except in compliance
  71430. * with the License. You may obtain a copy of the License at
  71431. *
  71432. * http://www.apache.org/licenses/LICENSE-2.0
  71433. *
  71434. * Unless required by applicable law or agreed to in writing,
  71435. * software distributed under the License is distributed on an
  71436. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71437. * KIND, either express or implied. See the License for the
  71438. * specific language governing permissions and limitations
  71439. * under the License.
  71440. */
  71441. registerProcessor({
  71442. // `dataZoomProcessor` will only be performed in needed series. Consider if
  71443. // there is a line series and a pie series, it is better not to update the
  71444. // line series if only pie series is needed to be updated.
  71445. getTargetSeries: function (ecModel) {
  71446. var seriesModelMap = createHashMap();
  71447. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  71448. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  71449. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  71450. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  71451. seriesModelMap.set(seriesModel.uid, seriesModel);
  71452. });
  71453. });
  71454. });
  71455. return seriesModelMap;
  71456. },
  71457. modifyOutputEnd: true,
  71458. // Consider appendData, where filter should be performed. Because data process is
  71459. // in block mode currently, it is not need to worry about that the overallProgress
  71460. // execute every frame.
  71461. overallReset: function (ecModel, api) {
  71462. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  71463. // We calculate window and reset axis here but not in model
  71464. // init stage and not after action dispatch handler, because
  71465. // reset should be called after seriesData.restoreData.
  71466. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  71467. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  71468. });
  71469. // Caution: data zoom filtering is order sensitive when using
  71470. // percent range and no min/max/scale set on axis.
  71471. // For example, we have dataZoom definition:
  71472. // [
  71473. // {xAxisIndex: 0, start: 30, end: 70},
  71474. // {yAxisIndex: 0, start: 20, end: 80}
  71475. // ]
  71476. // In this case, [20, 80] of y-dataZoom should be based on data
  71477. // that have filtered by x-dataZoom using range of [30, 70],
  71478. // but should not be based on full raw data. Thus sliding
  71479. // x-dataZoom will change both ranges of xAxis and yAxis,
  71480. // while sliding y-dataZoom will only change the range of yAxis.
  71481. // So we should filter x-axis after reset x-axis immediately,
  71482. // and then reset y-axis and filter y-axis.
  71483. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  71484. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  71485. });
  71486. });
  71487. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  71488. // Fullfill all of the range props so that user
  71489. // is able to get them from chart.getOption().
  71490. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  71491. var percentRange = axisProxy.getDataPercentWindow();
  71492. var valueRange = axisProxy.getDataValueWindow();
  71493. dataZoomModel.setRawRange({
  71494. start: percentRange[0],
  71495. end: percentRange[1],
  71496. startValue: valueRange[0],
  71497. endValue: valueRange[1]
  71498. }, true);
  71499. });
  71500. }
  71501. });
  71502. /*
  71503. * Licensed to the Apache Software Foundation (ASF) under one
  71504. * or more contributor license agreements. See the NOTICE file
  71505. * distributed with this work for additional information
  71506. * regarding copyright ownership. The ASF licenses this file
  71507. * to you under the Apache License, Version 2.0 (the
  71508. * "License"); you may not use this file except in compliance
  71509. * with the License. You may obtain a copy of the License at
  71510. *
  71511. * http://www.apache.org/licenses/LICENSE-2.0
  71512. *
  71513. * Unless required by applicable law or agreed to in writing,
  71514. * software distributed under the License is distributed on an
  71515. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71516. * KIND, either express or implied. See the License for the
  71517. * specific language governing permissions and limitations
  71518. * under the License.
  71519. */
  71520. registerAction('dataZoom', function (payload, ecModel) {
  71521. var linkedNodesFinder = createLinkedNodesFinder(
  71522. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  71523. eachAxisDim$1,
  71524. function (model, dimNames) {
  71525. return model.get(dimNames.axisIndex);
  71526. }
  71527. );
  71528. var effectedModels = [];
  71529. ecModel.eachComponent(
  71530. {mainType: 'dataZoom', query: payload},
  71531. function (model, index) {
  71532. effectedModels.push.apply(
  71533. effectedModels, linkedNodesFinder(model).nodes
  71534. );
  71535. }
  71536. );
  71537. each$1(effectedModels, function (dataZoomModel, index) {
  71538. dataZoomModel.setRawRange({
  71539. start: payload.start,
  71540. end: payload.end,
  71541. startValue: payload.startValue,
  71542. endValue: payload.endValue
  71543. });
  71544. });
  71545. });
  71546. /*
  71547. * Licensed to the Apache Software Foundation (ASF) under one
  71548. * or more contributor license agreements. See the NOTICE file
  71549. * distributed with this work for additional information
  71550. * regarding copyright ownership. The ASF licenses this file
  71551. * to you under the Apache License, Version 2.0 (the
  71552. * "License"); you may not use this file except in compliance
  71553. * with the License. You may obtain a copy of the License at
  71554. *
  71555. * http://www.apache.org/licenses/LICENSE-2.0
  71556. *
  71557. * Unless required by applicable law or agreed to in writing,
  71558. * software distributed under the License is distributed on an
  71559. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71560. * KIND, either express or implied. See the License for the
  71561. * specific language governing permissions and limitations
  71562. * under the License.
  71563. */
  71564. /**
  71565. * DataZoom component entry
  71566. */
  71567. /*
  71568. * Licensed to the Apache Software Foundation (ASF) under one
  71569. * or more contributor license agreements. See the NOTICE file
  71570. * distributed with this work for additional information
  71571. * regarding copyright ownership. The ASF licenses this file
  71572. * to you under the Apache License, Version 2.0 (the
  71573. * "License"); you may not use this file except in compliance
  71574. * with the License. You may obtain a copy of the License at
  71575. *
  71576. * http://www.apache.org/licenses/LICENSE-2.0
  71577. *
  71578. * Unless required by applicable law or agreed to in writing,
  71579. * software distributed under the License is distributed on an
  71580. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71581. * KIND, either express or implied. See the License for the
  71582. * specific language governing permissions and limitations
  71583. * under the License.
  71584. */
  71585. var each$24 = each$1;
  71586. var preprocessor$2 = function (option) {
  71587. var visualMap = option && option.visualMap;
  71588. if (!isArray(visualMap)) {
  71589. visualMap = visualMap ? [visualMap] : [];
  71590. }
  71591. each$24(visualMap, function (opt) {
  71592. if (!opt) {
  71593. return;
  71594. }
  71595. // rename splitList to pieces
  71596. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  71597. opt.pieces = opt.splitList;
  71598. delete opt.splitList;
  71599. }
  71600. var pieces = opt.pieces;
  71601. if (pieces && isArray(pieces)) {
  71602. each$24(pieces, function (piece) {
  71603. if (isObject$1(piece)) {
  71604. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  71605. piece.min = piece.start;
  71606. }
  71607. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  71608. piece.max = piece.end;
  71609. }
  71610. }
  71611. });
  71612. }
  71613. });
  71614. };
  71615. function has$1(obj, name) {
  71616. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  71617. }
  71618. /*
  71619. * Licensed to the Apache Software Foundation (ASF) under one
  71620. * or more contributor license agreements. See the NOTICE file
  71621. * distributed with this work for additional information
  71622. * regarding copyright ownership. The ASF licenses this file
  71623. * to you under the Apache License, Version 2.0 (the
  71624. * "License"); you may not use this file except in compliance
  71625. * with the License. You may obtain a copy of the License at
  71626. *
  71627. * http://www.apache.org/licenses/LICENSE-2.0
  71628. *
  71629. * Unless required by applicable law or agreed to in writing,
  71630. * software distributed under the License is distributed on an
  71631. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71632. * KIND, either express or implied. See the License for the
  71633. * specific language governing permissions and limitations
  71634. * under the License.
  71635. */
  71636. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  71637. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  71638. return (
  71639. !option.categories
  71640. && (
  71641. !(
  71642. option.pieces
  71643. ? option.pieces.length > 0
  71644. : option.splitNumber > 0
  71645. )
  71646. || option.calculable
  71647. )
  71648. )
  71649. ? 'continuous' : 'piecewise';
  71650. });
  71651. /*
  71652. * Licensed to the Apache Software Foundation (ASF) under one
  71653. * or more contributor license agreements. See the NOTICE file
  71654. * distributed with this work for additional information
  71655. * regarding copyright ownership. The ASF licenses this file
  71656. * to you under the Apache License, Version 2.0 (the
  71657. * "License"); you may not use this file except in compliance
  71658. * with the License. You may obtain a copy of the License at
  71659. *
  71660. * http://www.apache.org/licenses/LICENSE-2.0
  71661. *
  71662. * Unless required by applicable law or agreed to in writing,
  71663. * software distributed under the License is distributed on an
  71664. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71665. * KIND, either express or implied. See the License for the
  71666. * specific language governing permissions and limitations
  71667. * under the License.
  71668. */
  71669. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  71670. registerVisual(VISUAL_PRIORITY, {
  71671. createOnAllSeries: true,
  71672. reset: function (seriesModel, ecModel) {
  71673. var resetDefines = [];
  71674. ecModel.eachComponent('visualMap', function (visualMapModel) {
  71675. var pipelineContext = seriesModel.pipelineContext;
  71676. if (!visualMapModel.isTargetSeries(seriesModel)
  71677. || (pipelineContext && pipelineContext.large)
  71678. ) {
  71679. return;
  71680. }
  71681. resetDefines.push(incrementalApplyVisual(
  71682. visualMapModel.stateList,
  71683. visualMapModel.targetVisuals,
  71684. bind(visualMapModel.getValueState, visualMapModel),
  71685. visualMapModel.getDataDimension(seriesModel.getData())
  71686. ));
  71687. });
  71688. return resetDefines;
  71689. }
  71690. });
  71691. // Only support color.
  71692. registerVisual(VISUAL_PRIORITY, {
  71693. createOnAllSeries: true,
  71694. reset: function (seriesModel, ecModel) {
  71695. var data = seriesModel.getData();
  71696. var visualMetaList = [];
  71697. ecModel.eachComponent('visualMap', function (visualMapModel) {
  71698. if (visualMapModel.isTargetSeries(seriesModel)) {
  71699. var visualMeta = visualMapModel.getVisualMeta(
  71700. bind(getColorVisual, null, seriesModel, visualMapModel)
  71701. ) || {stops: [], outerColors: []};
  71702. var concreteDim = visualMapModel.getDataDimension(data);
  71703. var dimInfo = data.getDimensionInfo(concreteDim);
  71704. if (dimInfo != null) {
  71705. // visualMeta.dimension should be dimension index, but not concrete dimension.
  71706. visualMeta.dimension = dimInfo.index;
  71707. visualMetaList.push(visualMeta);
  71708. }
  71709. }
  71710. });
  71711. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  71712. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  71713. }
  71714. });
  71715. // FIXME
  71716. // performance and export for heatmap?
  71717. // value can be Infinity or -Infinity
  71718. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  71719. var mappings = visualMapModel.targetVisuals[valueState];
  71720. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  71721. var resultVisual = {
  71722. color: seriesModel.getData().getVisual('color') // default color.
  71723. };
  71724. for (var i = 0, len = visualTypes.length; i < len; i++) {
  71725. var type = visualTypes[i];
  71726. var mapping = mappings[
  71727. type === 'opacity' ? '__alphaForOpacity' : type
  71728. ];
  71729. mapping && mapping.applyVisual(value, getVisual, setVisual);
  71730. }
  71731. return resultVisual.color;
  71732. function getVisual(key) {
  71733. return resultVisual[key];
  71734. }
  71735. function setVisual(key, value) {
  71736. resultVisual[key] = value;
  71737. }
  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. /**
  71758. * @file Visual mapping.
  71759. */
  71760. var visualDefault = {
  71761. /**
  71762. * @public
  71763. */
  71764. get: function (visualType, key, isCategory) {
  71765. var value = clone(
  71766. (defaultOption$3[visualType] || {})[key]
  71767. );
  71768. return isCategory
  71769. ? (isArray(value) ? value[value.length - 1] : value)
  71770. : value;
  71771. }
  71772. };
  71773. var defaultOption$3 = {
  71774. color: {
  71775. active: ['#006edd', '#e0ffff'],
  71776. inactive: ['rgba(0,0,0,0)']
  71777. },
  71778. colorHue: {
  71779. active: [0, 360],
  71780. inactive: [0, 0]
  71781. },
  71782. colorSaturation: {
  71783. active: [0.3, 1],
  71784. inactive: [0, 0]
  71785. },
  71786. colorLightness: {
  71787. active: [0.9, 0.5],
  71788. inactive: [0, 0]
  71789. },
  71790. colorAlpha: {
  71791. active: [0.3, 1],
  71792. inactive: [0, 0]
  71793. },
  71794. opacity: {
  71795. active: [0.3, 1],
  71796. inactive: [0, 0]
  71797. },
  71798. symbol: {
  71799. active: ['circle', 'roundRect', 'diamond'],
  71800. inactive: ['none']
  71801. },
  71802. symbolSize: {
  71803. active: [10, 50],
  71804. inactive: [0, 0]
  71805. }
  71806. };
  71807. /*
  71808. * Licensed to the Apache Software Foundation (ASF) under one
  71809. * or more contributor license agreements. See the NOTICE file
  71810. * distributed with this work for additional information
  71811. * regarding copyright ownership. The ASF licenses this file
  71812. * to you under the Apache License, Version 2.0 (the
  71813. * "License"); you may not use this file except in compliance
  71814. * with the License. You may obtain a copy of the License at
  71815. *
  71816. * http://www.apache.org/licenses/LICENSE-2.0
  71817. *
  71818. * Unless required by applicable law or agreed to in writing,
  71819. * software distributed under the License is distributed on an
  71820. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71821. * KIND, either express or implied. See the License for the
  71822. * specific language governing permissions and limitations
  71823. * under the License.
  71824. */
  71825. var mapVisual$2 = VisualMapping.mapVisual;
  71826. var eachVisual = VisualMapping.eachVisual;
  71827. var isArray$3 = isArray;
  71828. var each$25 = each$1;
  71829. var asc$3 = asc;
  71830. var linearMap$2 = linearMap;
  71831. var noop$2 = noop;
  71832. var VisualMapModel = extendComponentModel({
  71833. type: 'visualMap',
  71834. dependencies: ['series'],
  71835. /**
  71836. * @readOnly
  71837. * @type {Array.<string>}
  71838. */
  71839. stateList: ['inRange', 'outOfRange'],
  71840. /**
  71841. * @readOnly
  71842. * @type {Array.<string>}
  71843. */
  71844. replacableOptionKeys: [
  71845. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  71846. ],
  71847. /**
  71848. * [lowerBound, upperBound]
  71849. *
  71850. * @readOnly
  71851. * @type {Array.<number>}
  71852. */
  71853. dataBound: [-Infinity, Infinity],
  71854. /**
  71855. * @readOnly
  71856. * @type {string|Object}
  71857. */
  71858. layoutMode: {type: 'box', ignoreSize: true},
  71859. /**
  71860. * @protected
  71861. */
  71862. defaultOption: {
  71863. show: true,
  71864. zlevel: 0,
  71865. z: 4,
  71866. seriesIndex: 'all', // 'all' or null/undefined: all series.
  71867. // A number or an array of number: the specified series.
  71868. // set min: 0, max: 200, only for campatible with ec2.
  71869. // In fact min max should not have default value.
  71870. min: 0, // min value, must specified if pieces is not specified.
  71871. max: 200, // max value, must specified if pieces is not specified.
  71872. dimension: null,
  71873. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  71874. // 'symbol', 'symbolSize'
  71875. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  71876. // 'colorLightness', 'colorAlpha',
  71877. // 'symbol', 'symbolSize'
  71878. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  71879. right: null, // The same as left.
  71880. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  71881. bottom: 0, // The same as top.
  71882. itemWidth: null,
  71883. itemHeight: null,
  71884. inverse: false,
  71885. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  71886. backgroundColor: 'rgba(0,0,0,0)',
  71887. borderColor: '#ccc', // 值域边框颜色
  71888. contentColor: '#5793f3',
  71889. inactiveColor: '#aaa',
  71890. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  71891. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  71892. // 接受数组分别设定上右下左边距,同css
  71893. textGap: 10, //
  71894. precision: 0, // 小数精度,默认为0,无小数点
  71895. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  71896. formatter: null,
  71897. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  71898. textStyle: {
  71899. color: '#333' // 值域文字颜色
  71900. }
  71901. },
  71902. /**
  71903. * @protected
  71904. */
  71905. init: function (option, parentModel, ecModel) {
  71906. /**
  71907. * @private
  71908. * @type {Array.<number>}
  71909. */
  71910. this._dataExtent;
  71911. /**
  71912. * @readOnly
  71913. */
  71914. this.targetVisuals = {};
  71915. /**
  71916. * @readOnly
  71917. */
  71918. this.controllerVisuals = {};
  71919. /**
  71920. * @readOnly
  71921. */
  71922. this.textStyleModel;
  71923. /**
  71924. * [width, height]
  71925. * @readOnly
  71926. * @type {Array.<number>}
  71927. */
  71928. this.itemSize;
  71929. this.mergeDefaultAndTheme(option, ecModel);
  71930. },
  71931. /**
  71932. * @protected
  71933. */
  71934. optionUpdated: function (newOption, isInit) {
  71935. var thisOption = this.option;
  71936. // FIXME
  71937. // necessary?
  71938. // Disable realtime view update if canvas is not supported.
  71939. if (!env$1.canvasSupported) {
  71940. thisOption.realtime = false;
  71941. }
  71942. !isInit && replaceVisualOption(
  71943. thisOption, newOption, this.replacableOptionKeys
  71944. );
  71945. this.textStyleModel = this.getModel('textStyle');
  71946. this.resetItemSize();
  71947. this.completeVisualOption();
  71948. },
  71949. /**
  71950. * @protected
  71951. */
  71952. resetVisual: function (supplementVisualOption) {
  71953. var stateList = this.stateList;
  71954. supplementVisualOption = bind(supplementVisualOption, this);
  71955. this.controllerVisuals = createVisualMappings(
  71956. this.option.controller, stateList, supplementVisualOption
  71957. );
  71958. this.targetVisuals = createVisualMappings(
  71959. this.option.target, stateList, supplementVisualOption
  71960. );
  71961. },
  71962. /**
  71963. * @protected
  71964. * @return {Array.<number>} An array of series indices.
  71965. */
  71966. getTargetSeriesIndices: function () {
  71967. var optionSeriesIndex = this.option.seriesIndex;
  71968. var seriesIndices = [];
  71969. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  71970. this.ecModel.eachSeries(function (seriesModel, index) {
  71971. seriesIndices.push(index);
  71972. });
  71973. }
  71974. else {
  71975. seriesIndices = normalizeToArray(optionSeriesIndex);
  71976. }
  71977. return seriesIndices;
  71978. },
  71979. /**
  71980. * @public
  71981. */
  71982. eachTargetSeries: function (callback, context) {
  71983. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  71984. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  71985. }, this);
  71986. },
  71987. /**
  71988. * @pubilc
  71989. */
  71990. isTargetSeries: function (seriesModel) {
  71991. var is = false;
  71992. this.eachTargetSeries(function (model) {
  71993. model === seriesModel && (is = true);
  71994. });
  71995. return is;
  71996. },
  71997. /**
  71998. * @example
  71999. * this.formatValueText(someVal); // format single numeric value to text.
  72000. * this.formatValueText(someVal, true); // format single category value to text.
  72001. * this.formatValueText([min, max]); // format numeric min-max to text.
  72002. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  72003. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  72004. *
  72005. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  72006. * @param {boolean} [isCategory=false] Only available when value is number.
  72007. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  72008. * @return {string}
  72009. * @protected
  72010. */
  72011. formatValueText: function (value, isCategory, edgeSymbols) {
  72012. var option = this.option;
  72013. var precision = option.precision;
  72014. var dataBound = this.dataBound;
  72015. var formatter = option.formatter;
  72016. var isMinMax;
  72017. var textValue;
  72018. edgeSymbols = edgeSymbols || ['<', '>'];
  72019. if (isArray(value)) {
  72020. value = value.slice();
  72021. isMinMax = true;
  72022. }
  72023. textValue = isCategory
  72024. ? value
  72025. : (isMinMax
  72026. ? [toFixed(value[0]), toFixed(value[1])]
  72027. : toFixed(value)
  72028. );
  72029. if (isString(formatter)) {
  72030. return formatter
  72031. .replace('{value}', isMinMax ? textValue[0] : textValue)
  72032. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  72033. }
  72034. else if (isFunction$1(formatter)) {
  72035. return isMinMax
  72036. ? formatter(value[0], value[1])
  72037. : formatter(value);
  72038. }
  72039. if (isMinMax) {
  72040. if (value[0] === dataBound[0]) {
  72041. return edgeSymbols[0] + ' ' + textValue[1];
  72042. }
  72043. else if (value[1] === dataBound[1]) {
  72044. return edgeSymbols[1] + ' ' + textValue[0];
  72045. }
  72046. else {
  72047. return textValue[0] + ' - ' + textValue[1];
  72048. }
  72049. }
  72050. else { // Format single value (includes category case).
  72051. return textValue;
  72052. }
  72053. function toFixed(val) {
  72054. return val === dataBound[0]
  72055. ? 'min'
  72056. : val === dataBound[1]
  72057. ? 'max'
  72058. : (+val).toFixed(Math.min(precision, 20));
  72059. }
  72060. },
  72061. /**
  72062. * @protected
  72063. */
  72064. resetExtent: function () {
  72065. var thisOption = this.option;
  72066. // Can not calculate data extent by data here.
  72067. // Because series and data may be modified in processing stage.
  72068. // So we do not support the feature "auto min/max".
  72069. var extent = asc$3([thisOption.min, thisOption.max]);
  72070. this._dataExtent = extent;
  72071. },
  72072. /**
  72073. * @public
  72074. * @param {module:echarts/data/List} list
  72075. * @return {string} Concrete dimention. If return null/undefined,
  72076. * no dimension used.
  72077. */
  72078. getDataDimension: function (list) {
  72079. var optDim = this.option.dimension;
  72080. var listDimensions = list.dimensions;
  72081. if (optDim == null && !listDimensions.length) {
  72082. return;
  72083. }
  72084. if (optDim != null) {
  72085. return list.getDimension(optDim);
  72086. }
  72087. var dimNames = list.dimensions;
  72088. for (var i = dimNames.length - 1; i >= 0; i--) {
  72089. var dimName = dimNames[i];
  72090. var dimInfo = list.getDimensionInfo(dimName);
  72091. if (!dimInfo.isCalculationCoord) {
  72092. return dimName;
  72093. }
  72094. }
  72095. },
  72096. /**
  72097. * @public
  72098. * @override
  72099. */
  72100. getExtent: function () {
  72101. return this._dataExtent.slice();
  72102. },
  72103. /**
  72104. * @protected
  72105. */
  72106. completeVisualOption: function () {
  72107. var ecModel = this.ecModel;
  72108. var thisOption = this.option;
  72109. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  72110. var target = thisOption.target || (thisOption.target = {});
  72111. var controller = thisOption.controller || (thisOption.controller = {});
  72112. merge(target, base); // Do not override
  72113. merge(controller, base); // Do not override
  72114. var isCategory = this.isCategory();
  72115. completeSingle.call(this, target);
  72116. completeSingle.call(this, controller);
  72117. completeInactive.call(this, target, 'inRange', 'outOfRange');
  72118. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  72119. completeController.call(this, controller);
  72120. function completeSingle(base) {
  72121. // Compatible with ec2 dataRange.color.
  72122. // The mapping order of dataRange.color is: [high value, ..., low value]
  72123. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  72124. // Notice: ec2 has no inverse.
  72125. if (isArray$3(thisOption.color)
  72126. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  72127. // So adding color only when no inRange defined.
  72128. && !base.inRange
  72129. ) {
  72130. base.inRange = {color: thisOption.color.slice().reverse()};
  72131. }
  72132. // Compatible with previous logic, always give a defautl color, otherwise
  72133. // simple config with no inRange and outOfRange will not work.
  72134. // Originally we use visualMap.color as the default color, but setOption at
  72135. // the second time the default color will be erased. So we change to use
  72136. // constant DEFAULT_COLOR.
  72137. // If user do not want the defualt color, set inRange: {color: null}.
  72138. base.inRange = base.inRange || {color: ecModel.get('gradientColor')};
  72139. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  72140. each$25(this.stateList, function (state) {
  72141. var visualType = base[state];
  72142. if (isString(visualType)) {
  72143. var defa = visualDefault.get(visualType, 'active', isCategory);
  72144. if (defa) {
  72145. base[state] = {};
  72146. base[state][visualType] = defa;
  72147. }
  72148. else {
  72149. // Mark as not specified.
  72150. delete base[state];
  72151. }
  72152. }
  72153. }, this);
  72154. }
  72155. function completeInactive(base, stateExist, stateAbsent) {
  72156. var optExist = base[stateExist];
  72157. var optAbsent = base[stateAbsent];
  72158. if (optExist && !optAbsent) {
  72159. optAbsent = base[stateAbsent] = {};
  72160. each$25(optExist, function (visualData, visualType) {
  72161. if (!VisualMapping.isValidType(visualType)) {
  72162. return;
  72163. }
  72164. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  72165. if (defa != null) {
  72166. optAbsent[visualType] = defa;
  72167. // Compatibable with ec2:
  72168. // Only inactive color to rgba(0,0,0,0) can not
  72169. // make label transparent, so use opacity also.
  72170. if (visualType === 'color'
  72171. && !optAbsent.hasOwnProperty('opacity')
  72172. && !optAbsent.hasOwnProperty('colorAlpha')
  72173. ) {
  72174. optAbsent.opacity = [0, 0];
  72175. }
  72176. }
  72177. });
  72178. }
  72179. }
  72180. function completeController(controller) {
  72181. var symbolExists = (controller.inRange || {}).symbol
  72182. || (controller.outOfRange || {}).symbol;
  72183. var symbolSizeExists = (controller.inRange || {}).symbolSize
  72184. || (controller.outOfRange || {}).symbolSize;
  72185. var inactiveColor = this.get('inactiveColor');
  72186. each$25(this.stateList, function (state) {
  72187. var itemSize = this.itemSize;
  72188. var visuals = controller[state];
  72189. // Set inactive color for controller if no other color
  72190. // attr (like colorAlpha) specified.
  72191. if (!visuals) {
  72192. visuals = controller[state] = {
  72193. color: isCategory ? inactiveColor : [inactiveColor]
  72194. };
  72195. }
  72196. // Consistent symbol and symbolSize if not specified.
  72197. if (visuals.symbol == null) {
  72198. visuals.symbol = symbolExists
  72199. && clone(symbolExists)
  72200. || (isCategory ? 'roundRect' : ['roundRect']);
  72201. }
  72202. if (visuals.symbolSize == null) {
  72203. visuals.symbolSize = symbolSizeExists
  72204. && clone(symbolSizeExists)
  72205. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  72206. }
  72207. // Filter square and none.
  72208. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  72209. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  72210. });
  72211. // Normalize symbolSize
  72212. var symbolSize = visuals.symbolSize;
  72213. if (symbolSize != null) {
  72214. var max = -Infinity;
  72215. // symbolSize can be object when categories defined.
  72216. eachVisual(symbolSize, function (value) {
  72217. value > max && (max = value);
  72218. });
  72219. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  72220. return linearMap$2(value, [0, max], [0, itemSize[0]], true);
  72221. });
  72222. }
  72223. }, this);
  72224. }
  72225. },
  72226. /**
  72227. * @protected
  72228. */
  72229. resetItemSize: function () {
  72230. this.itemSize = [
  72231. parseFloat(this.get('itemWidth')),
  72232. parseFloat(this.get('itemHeight'))
  72233. ];
  72234. },
  72235. /**
  72236. * @public
  72237. */
  72238. isCategory: function () {
  72239. return !!this.option.categories;
  72240. },
  72241. /**
  72242. * @public
  72243. * @abstract
  72244. */
  72245. setSelected: noop$2,
  72246. /**
  72247. * @public
  72248. * @abstract
  72249. * @param {*|module:echarts/data/List} valueOrData
  72250. * @param {number} dataIndex
  72251. * @return {string} state See this.stateList
  72252. */
  72253. getValueState: noop$2,
  72254. /**
  72255. * FIXME
  72256. * Do not publish to thirt-part-dev temporarily
  72257. * util the interface is stable. (Should it return
  72258. * a function but not visual meta?)
  72259. *
  72260. * @pubilc
  72261. * @abstract
  72262. * @param {Function} getColorVisual
  72263. * params: value, valueState
  72264. * return: color
  72265. * @return {Object} visualMeta
  72266. * should includes {stops, outerColors}
  72267. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  72268. */
  72269. getVisualMeta: noop$2
  72270. });
  72271. /*
  72272. * Licensed to the Apache Software Foundation (ASF) under one
  72273. * or more contributor license agreements. See the NOTICE file
  72274. * distributed with this work for additional information
  72275. * regarding copyright ownership. The ASF licenses this file
  72276. * to you under the Apache License, Version 2.0 (the
  72277. * "License"); you may not use this file except in compliance
  72278. * with the License. You may obtain a copy of the License at
  72279. *
  72280. * http://www.apache.org/licenses/LICENSE-2.0
  72281. *
  72282. * Unless required by applicable law or agreed to in writing,
  72283. * software distributed under the License is distributed on an
  72284. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72285. * KIND, either express or implied. See the License for the
  72286. * specific language governing permissions and limitations
  72287. * under the License.
  72288. */
  72289. // Constant
  72290. var DEFAULT_BAR_BOUND = [20, 140];
  72291. var ContinuousModel = VisualMapModel.extend({
  72292. type: 'visualMap.continuous',
  72293. /**
  72294. * @protected
  72295. */
  72296. defaultOption: {
  72297. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  72298. calculable: false, // This prop effect default component type determine,
  72299. // See echarts/component/visualMap/typeDefaulter.
  72300. range: null, // selected range. In default case `range` is [min, max]
  72301. // and can auto change along with modification of min max,
  72302. // util use specifid a range.
  72303. realtime: true, // Whether realtime update.
  72304. itemHeight: null, // The length of the range control edge.
  72305. itemWidth: null, // The length of the other side.
  72306. hoverLink: true, // Enable hover highlight.
  72307. hoverLinkDataSize: null, // The size of hovered data.
  72308. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  72309. // If not specified, follow the value of `realtime`.
  72310. },
  72311. /**
  72312. * @override
  72313. */
  72314. optionUpdated: function (newOption, isInit) {
  72315. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  72316. this.resetExtent();
  72317. this.resetVisual(function (mappingOption) {
  72318. mappingOption.mappingMethod = 'linear';
  72319. mappingOption.dataExtent = this.getExtent();
  72320. });
  72321. this._resetRange();
  72322. },
  72323. /**
  72324. * @protected
  72325. * @override
  72326. */
  72327. resetItemSize: function () {
  72328. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  72329. var itemSize = this.itemSize;
  72330. this._orient === 'horizontal' && itemSize.reverse();
  72331. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  72332. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  72333. },
  72334. /**
  72335. * @private
  72336. */
  72337. _resetRange: function () {
  72338. var dataExtent = this.getExtent();
  72339. var range = this.option.range;
  72340. if (!range || range.auto) {
  72341. // `range` should always be array (so we dont use other
  72342. // value like 'auto') for user-friend. (consider getOption).
  72343. dataExtent.auto = 1;
  72344. this.option.range = dataExtent;
  72345. }
  72346. else if (isArray(range)) {
  72347. if (range[0] > range[1]) {
  72348. range.reverse();
  72349. }
  72350. range[0] = Math.max(range[0], dataExtent[0]);
  72351. range[1] = Math.min(range[1], dataExtent[1]);
  72352. }
  72353. },
  72354. /**
  72355. * @protected
  72356. * @override
  72357. */
  72358. completeVisualOption: function () {
  72359. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  72360. each$1(this.stateList, function (state) {
  72361. var symbolSize = this.option.controller[state].symbolSize;
  72362. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  72363. symbolSize[0] = 0; // For good looking.
  72364. }
  72365. }, this);
  72366. },
  72367. /**
  72368. * @override
  72369. */
  72370. setSelected: function (selected) {
  72371. this.option.range = selected.slice();
  72372. this._resetRange();
  72373. },
  72374. /**
  72375. * @public
  72376. */
  72377. getSelected: function () {
  72378. var dataExtent = this.getExtent();
  72379. var dataInterval = asc(
  72380. (this.get('range') || []).slice()
  72381. );
  72382. // Clamp
  72383. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  72384. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  72385. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  72386. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  72387. return dataInterval;
  72388. },
  72389. /**
  72390. * @override
  72391. */
  72392. getValueState: function (value) {
  72393. var range = this.option.range;
  72394. var dataExtent = this.getExtent();
  72395. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  72396. // range[1] is processed likewise.
  72397. return (
  72398. (range[0] <= dataExtent[0] || range[0] <= value)
  72399. && (range[1] >= dataExtent[1] || value <= range[1])
  72400. ) ? 'inRange' : 'outOfRange';
  72401. },
  72402. /**
  72403. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  72404. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  72405. */
  72406. findTargetDataIndices: function (range) {
  72407. var result = [];
  72408. this.eachTargetSeries(function (seriesModel) {
  72409. var dataIndices = [];
  72410. var data = seriesModel.getData();
  72411. data.each(this.getDataDimension(data), function (value, dataIndex) {
  72412. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  72413. }, this);
  72414. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  72415. }, this);
  72416. return result;
  72417. },
  72418. /**
  72419. * @implement
  72420. */
  72421. getVisualMeta: function (getColorVisual) {
  72422. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  72423. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  72424. var stops = [];
  72425. function setStop(value, valueState) {
  72426. stops.push({
  72427. value: value,
  72428. color: getColorVisual(value, valueState)
  72429. });
  72430. }
  72431. // Format to: outOfRange -- inRange -- outOfRange.
  72432. var iIdx = 0;
  72433. var oIdx = 0;
  72434. var iLen = iVals.length;
  72435. var oLen = oVals.length;
  72436. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  72437. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  72438. if (oVals[oIdx] < iVals[iIdx]) {
  72439. setStop(oVals[oIdx], 'outOfRange');
  72440. }
  72441. }
  72442. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  72443. // If range is full, value beyond min, max will be clamped.
  72444. // make a singularity
  72445. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  72446. setStop(iVals[iIdx], 'inRange');
  72447. }
  72448. for (var first = 1; oIdx < oLen; oIdx++) {
  72449. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  72450. // make a singularity
  72451. if (first) {
  72452. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  72453. first = 0;
  72454. }
  72455. setStop(oVals[oIdx], 'outOfRange');
  72456. }
  72457. }
  72458. var stopsLen = stops.length;
  72459. return {
  72460. stops: stops,
  72461. outerColors: [
  72462. stopsLen ? stops[0].color : 'transparent',
  72463. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  72464. ]
  72465. };
  72466. }
  72467. });
  72468. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  72469. if (dataExtent[0] === dataExtent[1]) {
  72470. return dataExtent.slice();
  72471. }
  72472. // When using colorHue mapping, it is not linear color any more.
  72473. // Moreover, canvas gradient seems not to be accurate linear.
  72474. // FIXME
  72475. // Should be arbitrary value 100? or based on pixel size?
  72476. var count = 200;
  72477. var step = (dataExtent[1] - dataExtent[0]) / count;
  72478. var value = dataExtent[0];
  72479. var stopValues = [];
  72480. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  72481. stopValues.push(value);
  72482. value += step;
  72483. }
  72484. stopValues.push(dataExtent[1]);
  72485. return stopValues;
  72486. }
  72487. /*
  72488. * Licensed to the Apache Software Foundation (ASF) under one
  72489. * or more contributor license agreements. See the NOTICE file
  72490. * distributed with this work for additional information
  72491. * regarding copyright ownership. The ASF licenses this file
  72492. * to you under the Apache License, Version 2.0 (the
  72493. * "License"); you may not use this file except in compliance
  72494. * with the License. You may obtain a copy of the License at
  72495. *
  72496. * http://www.apache.org/licenses/LICENSE-2.0
  72497. *
  72498. * Unless required by applicable law or agreed to in writing,
  72499. * software distributed under the License is distributed on an
  72500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72501. * KIND, either express or implied. See the License for the
  72502. * specific language governing permissions and limitations
  72503. * under the License.
  72504. */
  72505. var VisualMapView = extendComponentView({
  72506. type: 'visualMap',
  72507. /**
  72508. * @readOnly
  72509. * @type {Object}
  72510. */
  72511. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  72512. init: function (ecModel, api) {
  72513. /**
  72514. * @readOnly
  72515. * @type {module:echarts/model/Global}
  72516. */
  72517. this.ecModel = ecModel;
  72518. /**
  72519. * @readOnly
  72520. * @type {module:echarts/ExtensionAPI}
  72521. */
  72522. this.api = api;
  72523. /**
  72524. * @readOnly
  72525. * @type {module:echarts/component/visualMap/visualMapModel}
  72526. */
  72527. this.visualMapModel;
  72528. },
  72529. /**
  72530. * @protected
  72531. */
  72532. render: function (visualMapModel, ecModel, api, payload) {
  72533. this.visualMapModel = visualMapModel;
  72534. if (visualMapModel.get('show') === false) {
  72535. this.group.removeAll();
  72536. return;
  72537. }
  72538. this.doRender.apply(this, arguments);
  72539. },
  72540. /**
  72541. * @protected
  72542. */
  72543. renderBackground: function (group) {
  72544. var visualMapModel = this.visualMapModel;
  72545. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  72546. var rect = group.getBoundingRect();
  72547. group.add(new Rect({
  72548. z2: -1, // Lay background rect on the lowest layer.
  72549. silent: true,
  72550. shape: {
  72551. x: rect.x - padding[3],
  72552. y: rect.y - padding[0],
  72553. width: rect.width + padding[3] + padding[1],
  72554. height: rect.height + padding[0] + padding[2]
  72555. },
  72556. style: {
  72557. fill: visualMapModel.get('backgroundColor'),
  72558. stroke: visualMapModel.get('borderColor'),
  72559. lineWidth: visualMapModel.get('borderWidth')
  72560. }
  72561. }));
  72562. },
  72563. /**
  72564. * @protected
  72565. * @param {number} targetValue can be Infinity or -Infinity
  72566. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  72567. * @param {Object} [opts]
  72568. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  72569. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  72570. * @return {*} Visual value.
  72571. */
  72572. getControllerVisual: function (targetValue, visualCluster, opts) {
  72573. opts = opts || {};
  72574. var forceState = opts.forceState;
  72575. var visualMapModel = this.visualMapModel;
  72576. var visualObj = {};
  72577. // Default values.
  72578. if (visualCluster === 'symbol') {
  72579. visualObj.symbol = visualMapModel.get('itemSymbol');
  72580. }
  72581. if (visualCluster === 'color') {
  72582. var defaultColor = visualMapModel.get('contentColor');
  72583. visualObj.color = defaultColor;
  72584. }
  72585. function getter(key) {
  72586. return visualObj[key];
  72587. }
  72588. function setter(key, value) {
  72589. visualObj[key] = value;
  72590. }
  72591. var mappings = visualMapModel.controllerVisuals[
  72592. forceState || visualMapModel.getValueState(targetValue)
  72593. ];
  72594. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  72595. each$1(visualTypes, function (type) {
  72596. var visualMapping = mappings[type];
  72597. if (opts.convertOpacityToAlpha && type === 'opacity') {
  72598. type = 'colorAlpha';
  72599. visualMapping = mappings.__alphaForOpacity;
  72600. }
  72601. if (VisualMapping.dependsOn(type, visualCluster)) {
  72602. visualMapping && visualMapping.applyVisual(
  72603. targetValue, getter, setter
  72604. );
  72605. }
  72606. });
  72607. return visualObj[visualCluster];
  72608. },
  72609. /**
  72610. * @protected
  72611. */
  72612. positionGroup: function (group) {
  72613. var model = this.visualMapModel;
  72614. var api = this.api;
  72615. positionElement(
  72616. group,
  72617. model.getBoxLayoutParams(),
  72618. {width: api.getWidth(), height: api.getHeight()}
  72619. );
  72620. },
  72621. /**
  72622. * @protected
  72623. * @abstract
  72624. */
  72625. doRender: noop
  72626. });
  72627. /*
  72628. * Licensed to the Apache Software Foundation (ASF) under one
  72629. * or more contributor license agreements. See the NOTICE file
  72630. * distributed with this work for additional information
  72631. * regarding copyright ownership. The ASF licenses this file
  72632. * to you under the Apache License, Version 2.0 (the
  72633. * "License"); you may not use this file except in compliance
  72634. * with the License. You may obtain a copy of the License at
  72635. *
  72636. * http://www.apache.org/licenses/LICENSE-2.0
  72637. *
  72638. * Unless required by applicable law or agreed to in writing,
  72639. * software distributed under the License is distributed on an
  72640. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72641. * KIND, either express or implied. See the License for the
  72642. * specific language governing permissions and limitations
  72643. * under the License.
  72644. */
  72645. /**
  72646. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  72647. * @param {module:echarts/ExtensionAPI} api
  72648. * @param {Array.<number>} itemSize always [short, long]
  72649. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  72650. */
  72651. function getItemAlign(visualMapModel, api, itemSize) {
  72652. var modelOption = visualMapModel.option;
  72653. var itemAlign = modelOption.align;
  72654. if (itemAlign != null && itemAlign !== 'auto') {
  72655. return itemAlign;
  72656. }
  72657. // Auto decision align.
  72658. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  72659. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  72660. var paramsSet = [
  72661. ['left', 'right', 'width'],
  72662. ['top', 'bottom', 'height']
  72663. ];
  72664. var reals = paramsSet[realIndex];
  72665. var fakeValue = [0, null, 10];
  72666. var layoutInput = {};
  72667. for (var i = 0; i < 3; i++) {
  72668. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  72669. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  72670. }
  72671. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  72672. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  72673. return reals[
  72674. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  72675. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  72676. ];
  72677. }
  72678. /**
  72679. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  72680. * dataIndexInside means filtered index.
  72681. */
  72682. function convertDataIndex(batch) {
  72683. each$1(batch || [], function (batchItem) {
  72684. if (batch.dataIndex != null) {
  72685. batch.dataIndexInside = batch.dataIndex;
  72686. batch.dataIndex = null;
  72687. }
  72688. });
  72689. return batch;
  72690. }
  72691. /*
  72692. * Licensed to the Apache Software Foundation (ASF) under one
  72693. * or more contributor license agreements. See the NOTICE file
  72694. * distributed with this work for additional information
  72695. * regarding copyright ownership. The ASF licenses this file
  72696. * to you under the Apache License, Version 2.0 (the
  72697. * "License"); you may not use this file except in compliance
  72698. * with the License. You may obtain a copy of the License at
  72699. *
  72700. * http://www.apache.org/licenses/LICENSE-2.0
  72701. *
  72702. * Unless required by applicable law or agreed to in writing,
  72703. * software distributed under the License is distributed on an
  72704. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72705. * KIND, either express or implied. See the License for the
  72706. * specific language governing permissions and limitations
  72707. * under the License.
  72708. */
  72709. var linearMap$3 = linearMap;
  72710. var each$26 = each$1;
  72711. var mathMin$7 = Math.min;
  72712. var mathMax$7 = Math.max;
  72713. // Arbitrary value
  72714. var HOVER_LINK_SIZE = 12;
  72715. var HOVER_LINK_OUT = 6;
  72716. // Notice:
  72717. // Any "interval" should be by the order of [low, high].
  72718. // "handle0" (handleIndex === 0) maps to
  72719. // low data value: this._dataInterval[0] and has low coord.
  72720. // "handle1" (handleIndex === 1) maps to
  72721. // high data value: this._dataInterval[1] and has high coord.
  72722. // The logic of transform is implemented in this._createBarGroup.
  72723. var ContinuousView = VisualMapView.extend({
  72724. type: 'visualMap.continuous',
  72725. /**
  72726. * @override
  72727. */
  72728. init: function () {
  72729. ContinuousView.superApply(this, 'init', arguments);
  72730. /**
  72731. * @private
  72732. */
  72733. this._shapes = {};
  72734. /**
  72735. * @private
  72736. */
  72737. this._dataInterval = [];
  72738. /**
  72739. * @private
  72740. */
  72741. this._handleEnds = [];
  72742. /**
  72743. * @private
  72744. */
  72745. this._orient;
  72746. /**
  72747. * @private
  72748. */
  72749. this._useHandle;
  72750. /**
  72751. * @private
  72752. */
  72753. this._hoverLinkDataIndices = [];
  72754. /**
  72755. * @private
  72756. */
  72757. this._dragging;
  72758. /**
  72759. * @private
  72760. */
  72761. this._hovering;
  72762. },
  72763. /**
  72764. * @protected
  72765. * @override
  72766. */
  72767. doRender: function (visualMapModel, ecModel, api, payload) {
  72768. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  72769. this._buildView();
  72770. }
  72771. },
  72772. /**
  72773. * @private
  72774. */
  72775. _buildView: function () {
  72776. this.group.removeAll();
  72777. var visualMapModel = this.visualMapModel;
  72778. var thisGroup = this.group;
  72779. this._orient = visualMapModel.get('orient');
  72780. this._useHandle = visualMapModel.get('calculable');
  72781. this._resetInterval();
  72782. this._renderBar(thisGroup);
  72783. var dataRangeText = visualMapModel.get('text');
  72784. this._renderEndsText(thisGroup, dataRangeText, 0);
  72785. this._renderEndsText(thisGroup, dataRangeText, 1);
  72786. // Do this for background size calculation.
  72787. this._updateView(true);
  72788. // After updating view, inner shapes is built completely,
  72789. // and then background can be rendered.
  72790. this.renderBackground(thisGroup);
  72791. // Real update view
  72792. this._updateView();
  72793. this._enableHoverLinkToSeries();
  72794. this._enableHoverLinkFromSeries();
  72795. this.positionGroup(thisGroup);
  72796. },
  72797. /**
  72798. * @private
  72799. */
  72800. _renderEndsText: function (group, dataRangeText, endsIndex) {
  72801. if (!dataRangeText) {
  72802. return;
  72803. }
  72804. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  72805. var text = dataRangeText[1 - endsIndex];
  72806. text = text != null ? text + '' : '';
  72807. var visualMapModel = this.visualMapModel;
  72808. var textGap = visualMapModel.get('textGap');
  72809. var itemSize = visualMapModel.itemSize;
  72810. var barGroup = this._shapes.barGroup;
  72811. var position = this._applyTransform(
  72812. [
  72813. itemSize[0] / 2,
  72814. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  72815. ],
  72816. barGroup
  72817. );
  72818. var align = this._applyTransform(
  72819. endsIndex === 0 ? 'bottom' : 'top',
  72820. barGroup
  72821. );
  72822. var orient = this._orient;
  72823. var textStyleModel = this.visualMapModel.textStyleModel;
  72824. this.group.add(new Text({
  72825. style: {
  72826. x: position[0],
  72827. y: position[1],
  72828. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  72829. textAlign: orient === 'horizontal' ? align : 'center',
  72830. text: text,
  72831. textFont: textStyleModel.getFont(),
  72832. textFill: textStyleModel.getTextColor()
  72833. }
  72834. }));
  72835. },
  72836. /**
  72837. * @private
  72838. */
  72839. _renderBar: function (targetGroup) {
  72840. var visualMapModel = this.visualMapModel;
  72841. var shapes = this._shapes;
  72842. var itemSize = visualMapModel.itemSize;
  72843. var orient = this._orient;
  72844. var useHandle = this._useHandle;
  72845. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  72846. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  72847. // Bar
  72848. barGroup.add(shapes.outOfRange = createPolygon());
  72849. barGroup.add(shapes.inRange = createPolygon(
  72850. null,
  72851. useHandle ? getCursor$1(this._orient) : null,
  72852. bind(this._dragHandle, this, 'all', false),
  72853. bind(this._dragHandle, this, 'all', true)
  72854. ));
  72855. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  72856. var textSize = mathMax$7(textRect.width, textRect.height);
  72857. // Handle
  72858. if (useHandle) {
  72859. shapes.handleThumbs = [];
  72860. shapes.handleLabels = [];
  72861. shapes.handleLabelPoints = [];
  72862. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  72863. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  72864. }
  72865. this._createIndicator(barGroup, itemSize, textSize, orient);
  72866. targetGroup.add(barGroup);
  72867. },
  72868. /**
  72869. * @private
  72870. */
  72871. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  72872. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  72873. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  72874. var handleThumb = createPolygon(
  72875. createHandlePoints(handleIndex, textSize),
  72876. getCursor$1(this._orient),
  72877. onDrift,
  72878. onDragEnd
  72879. );
  72880. handleThumb.position[0] = itemSize[0];
  72881. barGroup.add(handleThumb);
  72882. // Text is always horizontal layout but should not be effected by
  72883. // transform (orient/inverse). So label is built separately but not
  72884. // use zrender/graphic/helper/RectText, and is located based on view
  72885. // group (according to handleLabelPoint) but not barGroup.
  72886. var textStyleModel = this.visualMapModel.textStyleModel;
  72887. var handleLabel = new Text({
  72888. draggable: true,
  72889. drift: onDrift,
  72890. onmousemove: function (e) {
  72891. // Fot mobile devicem, prevent screen slider on the button.
  72892. stop(e.event);
  72893. },
  72894. ondragend: onDragEnd,
  72895. style: {
  72896. x: 0, y: 0, text: '',
  72897. textFont: textStyleModel.getFont(),
  72898. textFill: textStyleModel.getTextColor()
  72899. }
  72900. });
  72901. this.group.add(handleLabel);
  72902. var handleLabelPoint = [
  72903. orient === 'horizontal'
  72904. ? textSize / 2
  72905. : textSize * 1.5,
  72906. orient === 'horizontal'
  72907. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  72908. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  72909. ];
  72910. var shapes = this._shapes;
  72911. shapes.handleThumbs[handleIndex] = handleThumb;
  72912. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  72913. shapes.handleLabels[handleIndex] = handleLabel;
  72914. },
  72915. /**
  72916. * @private
  72917. */
  72918. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  72919. var indicator = createPolygon([[0, 0]], 'move');
  72920. indicator.position[0] = itemSize[0];
  72921. indicator.attr({invisible: true, silent: true});
  72922. barGroup.add(indicator);
  72923. var textStyleModel = this.visualMapModel.textStyleModel;
  72924. var indicatorLabel = new Text({
  72925. silent: true,
  72926. invisible: true,
  72927. style: {
  72928. x: 0, y: 0, text: '',
  72929. textFont: textStyleModel.getFont(),
  72930. textFill: textStyleModel.getTextColor()
  72931. }
  72932. });
  72933. this.group.add(indicatorLabel);
  72934. var indicatorLabelPoint = [
  72935. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  72936. 0
  72937. ];
  72938. var shapes = this._shapes;
  72939. shapes.indicator = indicator;
  72940. shapes.indicatorLabel = indicatorLabel;
  72941. shapes.indicatorLabelPoint = indicatorLabelPoint;
  72942. },
  72943. /**
  72944. * @private
  72945. */
  72946. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  72947. if (!this._useHandle) {
  72948. return;
  72949. }
  72950. this._dragging = !isEnd;
  72951. if (!isEnd) {
  72952. // Transform dx, dy to bar coordination.
  72953. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  72954. this._updateInterval(handleIndex, vertex[1]);
  72955. // Considering realtime, update view should be executed
  72956. // before dispatch action.
  72957. this._updateView();
  72958. }
  72959. // dragEnd do not dispatch action when realtime.
  72960. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  72961. this.api.dispatchAction({
  72962. type: 'selectDataRange',
  72963. from: this.uid,
  72964. visualMapId: this.visualMapModel.id,
  72965. selected: this._dataInterval.slice()
  72966. });
  72967. }
  72968. if (isEnd) {
  72969. !this._hovering && this._clearHoverLinkToSeries();
  72970. }
  72971. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  72972. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  72973. }
  72974. },
  72975. /**
  72976. * @private
  72977. */
  72978. _resetInterval: function () {
  72979. var visualMapModel = this.visualMapModel;
  72980. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  72981. var dataExtent = visualMapModel.getExtent();
  72982. var sizeExtent = [0, visualMapModel.itemSize[1]];
  72983. this._handleEnds = [
  72984. linearMap$3(dataInterval[0], dataExtent, sizeExtent, true),
  72985. linearMap$3(dataInterval[1], dataExtent, sizeExtent, true)
  72986. ];
  72987. },
  72988. /**
  72989. * @private
  72990. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  72991. * @param {number} dx
  72992. * @param {number} dy
  72993. */
  72994. _updateInterval: function (handleIndex, delta) {
  72995. delta = delta || 0;
  72996. var visualMapModel = this.visualMapModel;
  72997. var handleEnds = this._handleEnds;
  72998. var sizeExtent = [0, visualMapModel.itemSize[1]];
  72999. sliderMove(
  73000. delta,
  73001. handleEnds,
  73002. sizeExtent,
  73003. handleIndex,
  73004. // cross is forbiden
  73005. 0
  73006. );
  73007. var dataExtent = visualMapModel.getExtent();
  73008. // Update data interval.
  73009. this._dataInterval = [
  73010. linearMap$3(handleEnds[0], sizeExtent, dataExtent, true),
  73011. linearMap$3(handleEnds[1], sizeExtent, dataExtent, true)
  73012. ];
  73013. },
  73014. /**
  73015. * @private
  73016. */
  73017. _updateView: function (forSketch) {
  73018. var visualMapModel = this.visualMapModel;
  73019. var dataExtent = visualMapModel.getExtent();
  73020. var shapes = this._shapes;
  73021. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  73022. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  73023. var visualInRange = this._createBarVisual(
  73024. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  73025. );
  73026. var visualOutOfRange = this._createBarVisual(
  73027. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  73028. );
  73029. shapes.inRange
  73030. .setStyle({
  73031. fill: visualInRange.barColor,
  73032. opacity: visualInRange.opacity
  73033. })
  73034. .setShape('points', visualInRange.barPoints);
  73035. shapes.outOfRange
  73036. .setStyle({
  73037. fill: visualOutOfRange.barColor,
  73038. opacity: visualOutOfRange.opacity
  73039. })
  73040. .setShape('points', visualOutOfRange.barPoints);
  73041. this._updateHandle(inRangeHandleEnds, visualInRange);
  73042. },
  73043. /**
  73044. * @private
  73045. */
  73046. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  73047. var opts = {
  73048. forceState: forceState,
  73049. convertOpacityToAlpha: true
  73050. };
  73051. var colorStops = this._makeColorGradient(dataInterval, opts);
  73052. var symbolSizes = [
  73053. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  73054. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  73055. ];
  73056. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  73057. return {
  73058. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  73059. barPoints: barPoints,
  73060. handlesColor: [
  73061. colorStops[0].color,
  73062. colorStops[colorStops.length - 1].color
  73063. ]
  73064. };
  73065. },
  73066. /**
  73067. * @private
  73068. */
  73069. _makeColorGradient: function (dataInterval, opts) {
  73070. // Considering colorHue, which is not linear, so we have to sample
  73071. // to calculate gradient color stops, but not only caculate head
  73072. // and tail.
  73073. var sampleNumber = 100; // Arbitrary value.
  73074. var colorStops = [];
  73075. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  73076. colorStops.push({
  73077. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  73078. offset: 0
  73079. });
  73080. for (var i = 1; i < sampleNumber; i++) {
  73081. var currValue = dataInterval[0] + step * i;
  73082. if (currValue > dataInterval[1]) {
  73083. break;
  73084. }
  73085. colorStops.push({
  73086. color: this.getControllerVisual(currValue, 'color', opts),
  73087. offset: i / sampleNumber
  73088. });
  73089. }
  73090. colorStops.push({
  73091. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  73092. offset: 1
  73093. });
  73094. return colorStops;
  73095. },
  73096. /**
  73097. * @private
  73098. */
  73099. _createBarPoints: function (handleEnds, symbolSizes) {
  73100. var itemSize = this.visualMapModel.itemSize;
  73101. return [
  73102. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  73103. [itemSize[0], handleEnds[0]],
  73104. [itemSize[0], handleEnds[1]],
  73105. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  73106. ];
  73107. },
  73108. /**
  73109. * @private
  73110. */
  73111. _createBarGroup: function (itemAlign) {
  73112. var orient = this._orient;
  73113. var inverse = this.visualMapModel.get('inverse');
  73114. return new Group(
  73115. (orient === 'horizontal' && !inverse)
  73116. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  73117. : (orient === 'horizontal' && inverse)
  73118. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  73119. : (orient === 'vertical' && !inverse)
  73120. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  73121. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  73122. );
  73123. },
  73124. /**
  73125. * @private
  73126. */
  73127. _updateHandle: function (handleEnds, visualInRange) {
  73128. if (!this._useHandle) {
  73129. return;
  73130. }
  73131. var shapes = this._shapes;
  73132. var visualMapModel = this.visualMapModel;
  73133. var handleThumbs = shapes.handleThumbs;
  73134. var handleLabels = shapes.handleLabels;
  73135. each$26([0, 1], function (handleIndex) {
  73136. var handleThumb = handleThumbs[handleIndex];
  73137. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  73138. handleThumb.position[1] = handleEnds[handleIndex];
  73139. // Update handle label position.
  73140. var textPoint = applyTransform$1(
  73141. shapes.handleLabelPoints[handleIndex],
  73142. getTransform(handleThumb, this.group)
  73143. );
  73144. handleLabels[handleIndex].setStyle({
  73145. x: textPoint[0],
  73146. y: textPoint[1],
  73147. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  73148. textVerticalAlign: 'middle',
  73149. textAlign: this._applyTransform(
  73150. this._orient === 'horizontal'
  73151. ? (handleIndex === 0 ? 'bottom' : 'top')
  73152. : 'left',
  73153. shapes.barGroup
  73154. )
  73155. });
  73156. }, this);
  73157. },
  73158. /**
  73159. * @private
  73160. * @param {number} cursorValue
  73161. * @param {number} textValue
  73162. * @param {string} [rangeSymbol]
  73163. * @param {number} [halfHoverLinkSize]
  73164. */
  73165. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  73166. var visualMapModel = this.visualMapModel;
  73167. var dataExtent = visualMapModel.getExtent();
  73168. var itemSize = visualMapModel.itemSize;
  73169. var sizeExtent = [0, itemSize[1]];
  73170. var pos = linearMap$3(cursorValue, dataExtent, sizeExtent, true);
  73171. var shapes = this._shapes;
  73172. var indicator = shapes.indicator;
  73173. if (!indicator) {
  73174. return;
  73175. }
  73176. indicator.position[1] = pos;
  73177. indicator.attr('invisible', false);
  73178. indicator.setShape('points', createIndicatorPoints(
  73179. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  73180. ));
  73181. var opts = {convertOpacityToAlpha: true};
  73182. var color = this.getControllerVisual(cursorValue, 'color', opts);
  73183. indicator.setStyle('fill', color);
  73184. // Update handle label position.
  73185. var textPoint = applyTransform$1(
  73186. shapes.indicatorLabelPoint,
  73187. getTransform(indicator, this.group)
  73188. );
  73189. var indicatorLabel = shapes.indicatorLabel;
  73190. indicatorLabel.attr('invisible', false);
  73191. var align = this._applyTransform('left', shapes.barGroup);
  73192. var orient = this._orient;
  73193. indicatorLabel.setStyle({
  73194. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  73195. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  73196. textAlign: orient === 'horizontal' ? 'center' : align,
  73197. x: textPoint[0],
  73198. y: textPoint[1]
  73199. });
  73200. },
  73201. /**
  73202. * @private
  73203. */
  73204. _enableHoverLinkToSeries: function () {
  73205. var self = this;
  73206. this._shapes.barGroup
  73207. .on('mousemove', function (e) {
  73208. self._hovering = true;
  73209. if (!self._dragging) {
  73210. var itemSize = self.visualMapModel.itemSize;
  73211. var pos = self._applyTransform(
  73212. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  73213. );
  73214. // For hover link show when hover handle, which might be
  73215. // below or upper than sizeExtent.
  73216. pos[1] = mathMin$7(mathMax$7(0, pos[1]), itemSize[1]);
  73217. self._doHoverLinkToSeries(
  73218. pos[1],
  73219. 0 <= pos[0] && pos[0] <= itemSize[0]
  73220. );
  73221. }
  73222. })
  73223. .on('mouseout', function () {
  73224. // When mouse is out of handle, hoverLink still need
  73225. // to be displayed when realtime is set as false.
  73226. self._hovering = false;
  73227. !self._dragging && self._clearHoverLinkToSeries();
  73228. });
  73229. },
  73230. /**
  73231. * @private
  73232. */
  73233. _enableHoverLinkFromSeries: function () {
  73234. var zr = this.api.getZr();
  73235. if (this.visualMapModel.option.hoverLink) {
  73236. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  73237. zr.on('mouseout', this._hideIndicator, this);
  73238. }
  73239. else {
  73240. this._clearHoverLinkFromSeries();
  73241. }
  73242. },
  73243. /**
  73244. * @private
  73245. */
  73246. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  73247. var visualMapModel = this.visualMapModel;
  73248. var itemSize = visualMapModel.itemSize;
  73249. if (!visualMapModel.option.hoverLink) {
  73250. return;
  73251. }
  73252. var sizeExtent = [0, itemSize[1]];
  73253. var dataExtent = visualMapModel.getExtent();
  73254. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  73255. cursorPos = mathMin$7(mathMax$7(sizeExtent[0], cursorPos), sizeExtent[1]);
  73256. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  73257. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  73258. var cursorValue = linearMap$3(cursorPos, sizeExtent, dataExtent, true);
  73259. var valueRange = [
  73260. linearMap$3(hoverRange[0], sizeExtent, dataExtent, true),
  73261. linearMap$3(hoverRange[1], sizeExtent, dataExtent, true)
  73262. ];
  73263. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  73264. // where china and india has very large population.
  73265. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  73266. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  73267. // Do not show indicator when mouse is over handle,
  73268. // otherwise labels overlap, especially when dragging.
  73269. if (hoverOnBar) {
  73270. if (valueRange[0] === -Infinity) {
  73271. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  73272. }
  73273. else if (valueRange[1] === Infinity) {
  73274. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  73275. }
  73276. else {
  73277. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  73278. }
  73279. }
  73280. // When realtime is set as false, handles, which are in barGroup,
  73281. // also trigger hoverLink, which help user to realize where they
  73282. // focus on when dragging. (see test/heatmap-large.html)
  73283. // When realtime is set as true, highlight will not show when hover
  73284. // handle, because the label on handle, which displays a exact value
  73285. // but not range, might mislead users.
  73286. var oldBatch = this._hoverLinkDataIndices;
  73287. var newBatch = [];
  73288. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  73289. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  73290. }
  73291. var resultBatches = compressBatches(oldBatch, newBatch);
  73292. this._dispatchHighDown('downplay', convertDataIndex(resultBatches[0]));
  73293. this._dispatchHighDown('highlight', convertDataIndex(resultBatches[1]));
  73294. },
  73295. /**
  73296. * @private
  73297. */
  73298. _hoverLinkFromSeriesMouseOver: function (e) {
  73299. var el = e.target;
  73300. var visualMapModel = this.visualMapModel;
  73301. if (!el || el.dataIndex == null) {
  73302. return;
  73303. }
  73304. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  73305. if (!visualMapModel.isTargetSeries(dataModel)) {
  73306. return;
  73307. }
  73308. var data = dataModel.getData(el.dataType);
  73309. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  73310. if (!isNaN(value)) {
  73311. this._showIndicator(value, value);
  73312. }
  73313. },
  73314. /**
  73315. * @private
  73316. */
  73317. _hideIndicator: function () {
  73318. var shapes = this._shapes;
  73319. shapes.indicator && shapes.indicator.attr('invisible', true);
  73320. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  73321. },
  73322. /**
  73323. * @private
  73324. */
  73325. _clearHoverLinkToSeries: function () {
  73326. this._hideIndicator();
  73327. var indices = this._hoverLinkDataIndices;
  73328. this._dispatchHighDown('downplay', convertDataIndex(indices));
  73329. indices.length = 0;
  73330. },
  73331. /**
  73332. * @private
  73333. */
  73334. _clearHoverLinkFromSeries: function () {
  73335. this._hideIndicator();
  73336. var zr = this.api.getZr();
  73337. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  73338. zr.off('mouseout', this._hideIndicator);
  73339. },
  73340. /**
  73341. * @private
  73342. */
  73343. _applyTransform: function (vertex, element, inverse, global) {
  73344. var transform = getTransform(element, global ? null : this.group);
  73345. return graphic[
  73346. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  73347. ](vertex, transform, inverse);
  73348. },
  73349. /**
  73350. * @private
  73351. */
  73352. _dispatchHighDown: function (type, batch) {
  73353. batch && batch.length && this.api.dispatchAction({
  73354. type: type,
  73355. batch: batch
  73356. });
  73357. },
  73358. /**
  73359. * @override
  73360. */
  73361. dispose: function () {
  73362. this._clearHoverLinkFromSeries();
  73363. this._clearHoverLinkToSeries();
  73364. },
  73365. /**
  73366. * @override
  73367. */
  73368. remove: function () {
  73369. this._clearHoverLinkFromSeries();
  73370. this._clearHoverLinkToSeries();
  73371. }
  73372. });
  73373. function createPolygon(points, cursor, onDrift, onDragEnd) {
  73374. return new Polygon({
  73375. shape: {points: points},
  73376. draggable: !!onDrift,
  73377. cursor: cursor,
  73378. drift: onDrift,
  73379. onmousemove: function (e) {
  73380. // Fot mobile devicem, prevent screen slider on the button.
  73381. stop(e.event);
  73382. },
  73383. ondragend: onDragEnd
  73384. });
  73385. }
  73386. function createHandlePoints(handleIndex, textSize) {
  73387. return handleIndex === 0
  73388. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  73389. : [[0, 0], [textSize, 0], [textSize, textSize]];
  73390. }
  73391. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  73392. return isRange
  73393. ? [ // indicate range
  73394. [0, -mathMin$7(halfHoverLinkSize, mathMax$7(pos, 0))],
  73395. [HOVER_LINK_OUT, 0],
  73396. [0, mathMin$7(halfHoverLinkSize, mathMax$7(extentMax - pos, 0))]
  73397. ]
  73398. : [ // indicate single value
  73399. [0, 0], [5, -5], [5, 5]
  73400. ];
  73401. }
  73402. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  73403. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  73404. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  73405. if (hoverLinkDataSize) {
  73406. halfHoverLinkSize = linearMap$3(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  73407. }
  73408. return halfHoverLinkSize;
  73409. }
  73410. function useHoverLinkOnHandle(visualMapModel) {
  73411. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  73412. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  73413. }
  73414. function getCursor$1(orient) {
  73415. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  73416. }
  73417. /*
  73418. * Licensed to the Apache Software Foundation (ASF) under one
  73419. * or more contributor license agreements. See the NOTICE file
  73420. * distributed with this work for additional information
  73421. * regarding copyright ownership. The ASF licenses this file
  73422. * to you under the Apache License, Version 2.0 (the
  73423. * "License"); you may not use this file except in compliance
  73424. * with the License. You may obtain a copy of the License at
  73425. *
  73426. * http://www.apache.org/licenses/LICENSE-2.0
  73427. *
  73428. * Unless required by applicable law or agreed to in writing,
  73429. * software distributed under the License is distributed on an
  73430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73431. * KIND, either express or implied. See the License for the
  73432. * specific language governing permissions and limitations
  73433. * under the License.
  73434. */
  73435. var actionInfo$2 = {
  73436. type: 'selectDataRange',
  73437. event: 'dataRangeSelected',
  73438. // FIXME use updateView appears wrong
  73439. update: 'update'
  73440. };
  73441. registerAction(actionInfo$2, function (payload, ecModel) {
  73442. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  73443. model.setSelected(payload.selected);
  73444. });
  73445. });
  73446. /*
  73447. * Licensed to the Apache Software Foundation (ASF) under one
  73448. * or more contributor license agreements. See the NOTICE file
  73449. * distributed with this work for additional information
  73450. * regarding copyright ownership. The ASF licenses this file
  73451. * to you under the Apache License, Version 2.0 (the
  73452. * "License"); you may not use this file except in compliance
  73453. * with the License. You may obtain a copy of the License at
  73454. *
  73455. * http://www.apache.org/licenses/LICENSE-2.0
  73456. *
  73457. * Unless required by applicable law or agreed to in writing,
  73458. * software distributed under the License is distributed on an
  73459. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73460. * KIND, either express or implied. See the License for the
  73461. * specific language governing permissions and limitations
  73462. * under the License.
  73463. */
  73464. /**
  73465. * DataZoom component entry
  73466. */
  73467. registerPreprocessor(preprocessor$2);
  73468. /*
  73469. * Licensed to the Apache Software Foundation (ASF) under one
  73470. * or more contributor license agreements. See the NOTICE file
  73471. * distributed with this work for additional information
  73472. * regarding copyright ownership. The ASF licenses this file
  73473. * to you under the Apache License, Version 2.0 (the
  73474. * "License"); you may not use this file except in compliance
  73475. * with the License. You may obtain a copy of the License at
  73476. *
  73477. * http://www.apache.org/licenses/LICENSE-2.0
  73478. *
  73479. * Unless required by applicable law or agreed to in writing,
  73480. * software distributed under the License is distributed on an
  73481. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73482. * KIND, either express or implied. See the License for the
  73483. * specific language governing permissions and limitations
  73484. * under the License.
  73485. */
  73486. var PiecewiseModel = VisualMapModel.extend({
  73487. type: 'visualMap.piecewise',
  73488. /**
  73489. * Order Rule:
  73490. *
  73491. * option.categories / option.pieces / option.text / option.selected:
  73492. * If !option.inverse,
  73493. * Order when vertical: ['top', ..., 'bottom'].
  73494. * Order when horizontal: ['left', ..., 'right'].
  73495. * If option.inverse, the meaning of
  73496. * the order should be reversed.
  73497. *
  73498. * this._pieceList:
  73499. * The order is always [low, ..., high].
  73500. *
  73501. * Mapping from location to low-high:
  73502. * If !option.inverse
  73503. * When vertical, top is high.
  73504. * When horizontal, right is high.
  73505. * If option.inverse, reverse.
  73506. */
  73507. /**
  73508. * @protected
  73509. */
  73510. defaultOption: {
  73511. selected: null, // Object. If not specified, means selected.
  73512. // When pieces and splitNumber: {'0': true, '5': true}
  73513. // When categories: {'cate1': false, 'cate3': true}
  73514. // When selected === false, means all unselected.
  73515. minOpen: false, // Whether include values that smaller than `min`.
  73516. maxOpen: false, // Whether include values that bigger than `max`.
  73517. align: 'auto', // 'auto', 'left', 'right'
  73518. itemWidth: 20, // When put the controller vertically, it is the length of
  73519. // horizontal side of each item. Otherwise, vertical side.
  73520. itemHeight: 14, // When put the controller vertically, it is the length of
  73521. // vertical side of each item. Otherwise, horizontal side.
  73522. itemSymbol: 'roundRect',
  73523. pieceList: null, // Each item is Object, with some of those attrs:
  73524. // {min, max, lt, gt, lte, gte, value,
  73525. // color, colorSaturation, colorAlpha, opacity,
  73526. // symbol, symbolSize}, which customize the range or visual
  73527. // coding of the certain piece. Besides, see "Order Rule".
  73528. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  73529. // Attr min/max are ignored when categories set. See "Order Rule"
  73530. splitNumber: 5, // If set to 5, auto split five pieces equally.
  73531. // If set to 0 and component type not set, component type will be
  73532. // determined as "continuous". (It is less reasonable but for ec2
  73533. // compatibility, see echarts/component/visualMap/typeDefaulter)
  73534. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  73535. itemGap: 10, // The gap between two items, in px.
  73536. hoverLink: true, // Enable hover highlight.
  73537. showLabel: null // By default, when text is used, label will hide (the logic
  73538. // is remained for compatibility reason)
  73539. },
  73540. /**
  73541. * @override
  73542. */
  73543. optionUpdated: function (newOption, isInit) {
  73544. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  73545. /**
  73546. * The order is always [low, ..., high].
  73547. * [{text: string, interval: Array.<number>}, ...]
  73548. * @private
  73549. * @type {Array.<Object>}
  73550. */
  73551. this._pieceList = [];
  73552. this.resetExtent();
  73553. /**
  73554. * 'pieces', 'categories', 'splitNumber'
  73555. * @type {string}
  73556. */
  73557. var mode = this._mode = this._determineMode();
  73558. resetMethods[this._mode].call(this);
  73559. this._resetSelected(newOption, isInit);
  73560. var categories = this.option.categories;
  73561. this.resetVisual(function (mappingOption, state) {
  73562. if (mode === 'categories') {
  73563. mappingOption.mappingMethod = 'category';
  73564. mappingOption.categories = clone(categories);
  73565. }
  73566. else {
  73567. mappingOption.dataExtent = this.getExtent();
  73568. mappingOption.mappingMethod = 'piecewise';
  73569. mappingOption.pieceList = map(this._pieceList, function (piece) {
  73570. var piece = clone(piece);
  73571. if (state !== 'inRange') {
  73572. // FIXME
  73573. // outOfRange do not support special visual in pieces.
  73574. piece.visual = null;
  73575. }
  73576. return piece;
  73577. });
  73578. }
  73579. });
  73580. },
  73581. /**
  73582. * @protected
  73583. * @override
  73584. */
  73585. completeVisualOption: function () {
  73586. // Consider this case:
  73587. // visualMap: {
  73588. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  73589. // }
  73590. // where no inRange/outOfRange set but only pieces. So we should make
  73591. // default inRange/outOfRange for this case, otherwise visuals that only
  73592. // appear in `pieces` will not be taken into account in visual encoding.
  73593. var option = this.option;
  73594. var visualTypesInPieces = {};
  73595. var visualTypes = VisualMapping.listVisualTypes();
  73596. var isCategory = this.isCategory();
  73597. each$1(option.pieces, function (piece) {
  73598. each$1(visualTypes, function (visualType) {
  73599. if (piece.hasOwnProperty(visualType)) {
  73600. visualTypesInPieces[visualType] = 1;
  73601. }
  73602. });
  73603. });
  73604. each$1(visualTypesInPieces, function (v, visualType) {
  73605. var exists = 0;
  73606. each$1(this.stateList, function (state) {
  73607. exists |= has(option, state, visualType)
  73608. || has(option.target, state, visualType);
  73609. }, this);
  73610. !exists && each$1(this.stateList, function (state) {
  73611. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  73612. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  73613. );
  73614. });
  73615. }, this);
  73616. function has(obj, state, visualType) {
  73617. return obj && obj[state] && (
  73618. isObject$1(obj[state])
  73619. ? obj[state].hasOwnProperty(visualType)
  73620. : obj[state] === visualType // e.g., inRange: 'symbol'
  73621. );
  73622. }
  73623. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  73624. },
  73625. _resetSelected: function (newOption, isInit) {
  73626. var thisOption = this.option;
  73627. var pieceList = this._pieceList;
  73628. // Selected do not merge but all override.
  73629. var selected = (isInit ? thisOption : newOption).selected || {};
  73630. thisOption.selected = selected;
  73631. // Consider 'not specified' means true.
  73632. each$1(pieceList, function (piece, index) {
  73633. var key = this.getSelectedMapKey(piece);
  73634. if (!selected.hasOwnProperty(key)) {
  73635. selected[key] = true;
  73636. }
  73637. }, this);
  73638. if (thisOption.selectedMode === 'single') {
  73639. // Ensure there is only one selected.
  73640. var hasSel = false;
  73641. each$1(pieceList, function (piece, index) {
  73642. var key = this.getSelectedMapKey(piece);
  73643. if (selected[key]) {
  73644. hasSel
  73645. ? (selected[key] = false)
  73646. : (hasSel = true);
  73647. }
  73648. }, this);
  73649. }
  73650. // thisOption.selectedMode === 'multiple', default: all selected.
  73651. },
  73652. /**
  73653. * @public
  73654. */
  73655. getSelectedMapKey: function (piece) {
  73656. return this._mode === 'categories'
  73657. ? piece.value + '' : piece.index + '';
  73658. },
  73659. /**
  73660. * @public
  73661. */
  73662. getPieceList: function () {
  73663. return this._pieceList;
  73664. },
  73665. /**
  73666. * @private
  73667. * @return {string}
  73668. */
  73669. _determineMode: function () {
  73670. var option = this.option;
  73671. return option.pieces && option.pieces.length > 0
  73672. ? 'pieces'
  73673. : this.option.categories
  73674. ? 'categories'
  73675. : 'splitNumber';
  73676. },
  73677. /**
  73678. * @public
  73679. * @override
  73680. */
  73681. setSelected: function (selected) {
  73682. this.option.selected = clone(selected);
  73683. },
  73684. /**
  73685. * @public
  73686. * @override
  73687. */
  73688. getValueState: function (value) {
  73689. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  73690. return index != null
  73691. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  73692. ? 'inRange' : 'outOfRange'
  73693. )
  73694. : 'outOfRange';
  73695. },
  73696. /**
  73697. * @public
  73698. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  73699. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  73700. */
  73701. findTargetDataIndices: function (pieceIndex) {
  73702. var result = [];
  73703. this.eachTargetSeries(function (seriesModel) {
  73704. var dataIndices = [];
  73705. var data = seriesModel.getData();
  73706. data.each(this.getDataDimension(data), function (value, dataIndex) {
  73707. // Should always base on model pieceList, because it is order sensitive.
  73708. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  73709. pIdx === pieceIndex && dataIndices.push(dataIndex);
  73710. }, this);
  73711. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  73712. }, this);
  73713. return result;
  73714. },
  73715. /**
  73716. * @private
  73717. * @param {Object} piece piece.value or piece.interval is required.
  73718. * @return {number} Can be Infinity or -Infinity
  73719. */
  73720. getRepresentValue: function (piece) {
  73721. var representValue;
  73722. if (this.isCategory()) {
  73723. representValue = piece.value;
  73724. }
  73725. else {
  73726. if (piece.value != null) {
  73727. representValue = piece.value;
  73728. }
  73729. else {
  73730. var pieceInterval = piece.interval || [];
  73731. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  73732. ? 0
  73733. : (pieceInterval[0] + pieceInterval[1]) / 2;
  73734. }
  73735. }
  73736. return representValue;
  73737. },
  73738. getVisualMeta: function (getColorVisual) {
  73739. // Do not support category. (category axis is ordinal, numerical)
  73740. if (this.isCategory()) {
  73741. return;
  73742. }
  73743. var stops = [];
  73744. var outerColors = [];
  73745. var visualMapModel = this;
  73746. function setStop(interval, valueState) {
  73747. var representValue = visualMapModel.getRepresentValue({interval: interval});
  73748. if (!valueState) {
  73749. valueState = visualMapModel.getValueState(representValue);
  73750. }
  73751. var color = getColorVisual(representValue, valueState);
  73752. if (interval[0] === -Infinity) {
  73753. outerColors[0] = color;
  73754. }
  73755. else if (interval[1] === Infinity) {
  73756. outerColors[1] = color;
  73757. }
  73758. else {
  73759. stops.push(
  73760. {value: interval[0], color: color},
  73761. {value: interval[1], color: color}
  73762. );
  73763. }
  73764. }
  73765. // Suplement
  73766. var pieceList = this._pieceList.slice();
  73767. if (!pieceList.length) {
  73768. pieceList.push({interval: [-Infinity, Infinity]});
  73769. }
  73770. else {
  73771. var edge = pieceList[0].interval[0];
  73772. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  73773. edge = pieceList[pieceList.length - 1].interval[1];
  73774. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  73775. }
  73776. var curr = -Infinity;
  73777. each$1(pieceList, function (piece) {
  73778. var interval = piece.interval;
  73779. if (interval) {
  73780. // Fulfill gap.
  73781. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  73782. setStop(interval.slice());
  73783. curr = interval[1];
  73784. }
  73785. }, this);
  73786. return {stops: stops, outerColors: outerColors};
  73787. }
  73788. });
  73789. /**
  73790. * Key is this._mode
  73791. * @type {Object}
  73792. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  73793. */
  73794. var resetMethods = {
  73795. splitNumber: function () {
  73796. var thisOption = this.option;
  73797. var pieceList = this._pieceList;
  73798. var precision = Math.min(thisOption.precision, 20);
  73799. var dataExtent = this.getExtent();
  73800. var splitNumber = thisOption.splitNumber;
  73801. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  73802. thisOption.splitNumber = splitNumber;
  73803. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  73804. // Precision auto-adaption
  73805. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  73806. precision++;
  73807. }
  73808. thisOption.precision = precision;
  73809. splitStep = +splitStep.toFixed(precision);
  73810. var index = 0;
  73811. if (thisOption.minOpen) {
  73812. pieceList.push({
  73813. index: index++,
  73814. interval: [-Infinity, dataExtent[0]],
  73815. close: [0, 0]
  73816. });
  73817. }
  73818. for (
  73819. var curr = dataExtent[0], len = index + splitNumber;
  73820. index < len;
  73821. curr += splitStep
  73822. ) {
  73823. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  73824. pieceList.push({
  73825. index: index++,
  73826. interval: [curr, max],
  73827. close: [1, 1]
  73828. });
  73829. }
  73830. if (thisOption.maxOpen) {
  73831. pieceList.push({
  73832. index: index++,
  73833. interval: [dataExtent[1], Infinity],
  73834. close: [0, 0]
  73835. });
  73836. }
  73837. reformIntervals(pieceList);
  73838. each$1(pieceList, function (piece) {
  73839. piece.text = this.formatValueText(piece.interval);
  73840. }, this);
  73841. },
  73842. categories: function () {
  73843. var thisOption = this.option;
  73844. each$1(thisOption.categories, function (cate) {
  73845. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  73846. // 是否改一致。
  73847. this._pieceList.push({
  73848. text: this.formatValueText(cate, true),
  73849. value: cate
  73850. });
  73851. }, this);
  73852. // See "Order Rule".
  73853. normalizeReverse(thisOption, this._pieceList);
  73854. },
  73855. pieces: function () {
  73856. var thisOption = this.option;
  73857. var pieceList = this._pieceList;
  73858. each$1(thisOption.pieces, function (pieceListItem, index) {
  73859. if (!isObject$1(pieceListItem)) {
  73860. pieceListItem = {value: pieceListItem};
  73861. }
  73862. var item = {text: '', index: index};
  73863. if (pieceListItem.label != null) {
  73864. item.text = pieceListItem.label;
  73865. }
  73866. if (pieceListItem.hasOwnProperty('value')) {
  73867. var value = item.value = pieceListItem.value;
  73868. item.interval = [value, value];
  73869. item.close = [1, 1];
  73870. }
  73871. else {
  73872. // `min` `max` is legacy option.
  73873. // `lt` `gt` `lte` `gte` is recommanded.
  73874. var interval = item.interval = [];
  73875. var close = item.close = [0, 0];
  73876. var closeList = [1, 0, 1];
  73877. var infinityList = [-Infinity, Infinity];
  73878. var useMinMax = [];
  73879. for (var lg = 0; lg < 2; lg++) {
  73880. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  73881. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  73882. interval[lg] = pieceListItem[names[i]];
  73883. close[lg] = closeList[i];
  73884. useMinMax[lg] = i === 2;
  73885. }
  73886. interval[lg] == null && (interval[lg] = infinityList[lg]);
  73887. }
  73888. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  73889. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  73890. if (__DEV__) {
  73891. if (interval[0] > interval[1]) {
  73892. console.warn(
  73893. 'Piece ' + index + 'is illegal: ' + interval
  73894. + ' lower bound should not greater then uppper bound.'
  73895. );
  73896. }
  73897. }
  73898. if (interval[0] === interval[1] && close[0] && close[1]) {
  73899. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  73900. // we use value to lift the priority when min === max
  73901. item.value = interval[0];
  73902. }
  73903. }
  73904. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  73905. pieceList.push(item);
  73906. }, this);
  73907. // See "Order Rule".
  73908. normalizeReverse(thisOption, pieceList);
  73909. // Only pieces
  73910. reformIntervals(pieceList);
  73911. each$1(pieceList, function (piece) {
  73912. var close = piece.close;
  73913. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  73914. piece.text = piece.text || this.formatValueText(
  73915. piece.value != null ? piece.value : piece.interval,
  73916. false,
  73917. edgeSymbols
  73918. );
  73919. }, this);
  73920. }
  73921. };
  73922. function normalizeReverse(thisOption, pieceList) {
  73923. var inverse = thisOption.inverse;
  73924. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  73925. pieceList.reverse();
  73926. }
  73927. }
  73928. /*
  73929. * Licensed to the Apache Software Foundation (ASF) under one
  73930. * or more contributor license agreements. See the NOTICE file
  73931. * distributed with this work for additional information
  73932. * regarding copyright ownership. The ASF licenses this file
  73933. * to you under the Apache License, Version 2.0 (the
  73934. * "License"); you may not use this file except in compliance
  73935. * with the License. You may obtain a copy of the License at
  73936. *
  73937. * http://www.apache.org/licenses/LICENSE-2.0
  73938. *
  73939. * Unless required by applicable law or agreed to in writing,
  73940. * software distributed under the License is distributed on an
  73941. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73942. * KIND, either express or implied. See the License for the
  73943. * specific language governing permissions and limitations
  73944. * under the License.
  73945. */
  73946. var PiecewiseVisualMapView = VisualMapView.extend({
  73947. type: 'visualMap.piecewise',
  73948. /**
  73949. * @protected
  73950. * @override
  73951. */
  73952. doRender: function () {
  73953. var thisGroup = this.group;
  73954. thisGroup.removeAll();
  73955. var visualMapModel = this.visualMapModel;
  73956. var textGap = visualMapModel.get('textGap');
  73957. var textStyleModel = visualMapModel.textStyleModel;
  73958. var textFont = textStyleModel.getFont();
  73959. var textFill = textStyleModel.getTextColor();
  73960. var itemAlign = this._getItemAlign();
  73961. var itemSize = visualMapModel.itemSize;
  73962. var viewData = this._getViewData();
  73963. var endsText = viewData.endsText;
  73964. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  73965. endsText && this._renderEndsText(
  73966. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  73967. );
  73968. each$1(viewData.viewPieceList, renderItem, this);
  73969. endsText && this._renderEndsText(
  73970. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  73971. );
  73972. box(
  73973. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  73974. );
  73975. this.renderBackground(thisGroup);
  73976. this.positionGroup(thisGroup);
  73977. function renderItem(item) {
  73978. var piece = item.piece;
  73979. var itemGroup = new Group();
  73980. itemGroup.onclick = bind(this._onItemClick, this, piece);
  73981. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  73982. var representValue = visualMapModel.getRepresentValue(piece);
  73983. this._createItemSymbol(
  73984. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  73985. );
  73986. if (showLabel) {
  73987. var visualState = this.visualMapModel.getValueState(representValue);
  73988. itemGroup.add(new Text({
  73989. style: {
  73990. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  73991. y: itemSize[1] / 2,
  73992. text: piece.text,
  73993. textVerticalAlign: 'middle',
  73994. textAlign: itemAlign,
  73995. textFont: textFont,
  73996. textFill: textFill,
  73997. opacity: visualState === 'outOfRange' ? 0.5 : 1
  73998. }
  73999. }));
  74000. }
  74001. thisGroup.add(itemGroup);
  74002. }
  74003. },
  74004. /**
  74005. * @private
  74006. */
  74007. _enableHoverLink: function (itemGroup, pieceIndex) {
  74008. itemGroup
  74009. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  74010. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  74011. function onHoverLink(method) {
  74012. var visualMapModel = this.visualMapModel;
  74013. visualMapModel.option.hoverLink && this.api.dispatchAction({
  74014. type: method,
  74015. batch: convertDataIndex(
  74016. visualMapModel.findTargetDataIndices(pieceIndex)
  74017. )
  74018. });
  74019. }
  74020. },
  74021. /**
  74022. * @private
  74023. */
  74024. _getItemAlign: function () {
  74025. var visualMapModel = this.visualMapModel;
  74026. var modelOption = visualMapModel.option;
  74027. if (modelOption.orient === 'vertical') {
  74028. return getItemAlign(
  74029. visualMapModel, this.api, visualMapModel.itemSize
  74030. );
  74031. }
  74032. else { // horizontal, most case left unless specifying right.
  74033. var align = modelOption.align;
  74034. if (!align || align === 'auto') {
  74035. align = 'left';
  74036. }
  74037. return align;
  74038. }
  74039. },
  74040. /**
  74041. * @private
  74042. */
  74043. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  74044. if (!text) {
  74045. return;
  74046. }
  74047. var itemGroup = new Group();
  74048. var textStyleModel = this.visualMapModel.textStyleModel;
  74049. itemGroup.add(new Text({
  74050. style: {
  74051. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  74052. y: itemSize[1] / 2,
  74053. textVerticalAlign: 'middle',
  74054. textAlign: showLabel ? itemAlign : 'center',
  74055. text: text,
  74056. textFont: textStyleModel.getFont(),
  74057. textFill: textStyleModel.getTextColor()
  74058. }
  74059. }));
  74060. group.add(itemGroup);
  74061. },
  74062. /**
  74063. * @private
  74064. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  74065. */
  74066. _getViewData: function () {
  74067. var visualMapModel = this.visualMapModel;
  74068. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  74069. return {piece: piece, indexInModelPieceList: index};
  74070. });
  74071. var endsText = visualMapModel.get('text');
  74072. // Consider orient and inverse.
  74073. var orient = visualMapModel.get('orient');
  74074. var inverse = visualMapModel.get('inverse');
  74075. // Order of model pieceList is always [low, ..., high]
  74076. if (orient === 'horizontal' ? inverse : !inverse) {
  74077. viewPieceList.reverse();
  74078. }
  74079. // Origin order of endsText is [high, low]
  74080. else if (endsText) {
  74081. endsText = endsText.slice().reverse();
  74082. }
  74083. return {viewPieceList: viewPieceList, endsText: endsText};
  74084. },
  74085. /**
  74086. * @private
  74087. */
  74088. _createItemSymbol: function (group, representValue, shapeParam) {
  74089. group.add(createSymbol(
  74090. this.getControllerVisual(representValue, 'symbol'),
  74091. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  74092. this.getControllerVisual(representValue, 'color')
  74093. ));
  74094. },
  74095. /**
  74096. * @private
  74097. */
  74098. _onItemClick: function (piece) {
  74099. var visualMapModel = this.visualMapModel;
  74100. var option = visualMapModel.option;
  74101. var selected = clone(option.selected);
  74102. var newKey = visualMapModel.getSelectedMapKey(piece);
  74103. if (option.selectedMode === 'single') {
  74104. selected[newKey] = true;
  74105. each$1(selected, function (o, key) {
  74106. selected[key] = key === newKey;
  74107. });
  74108. }
  74109. else {
  74110. selected[newKey] = !selected[newKey];
  74111. }
  74112. this.api.dispatchAction({
  74113. type: 'selectDataRange',
  74114. from: this.uid,
  74115. visualMapId: this.visualMapModel.id,
  74116. selected: selected
  74117. });
  74118. }
  74119. });
  74120. /*
  74121. * Licensed to the Apache Software Foundation (ASF) under one
  74122. * or more contributor license agreements. See the NOTICE file
  74123. * distributed with this work for additional information
  74124. * regarding copyright ownership. The ASF licenses this file
  74125. * to you under the Apache License, Version 2.0 (the
  74126. * "License"); you may not use this file except in compliance
  74127. * with the License. You may obtain a copy of the License at
  74128. *
  74129. * http://www.apache.org/licenses/LICENSE-2.0
  74130. *
  74131. * Unless required by applicable law or agreed to in writing,
  74132. * software distributed under the License is distributed on an
  74133. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74134. * KIND, either express or implied. See the License for the
  74135. * specific language governing permissions and limitations
  74136. * under the License.
  74137. */
  74138. /**
  74139. * DataZoom component entry
  74140. */
  74141. registerPreprocessor(preprocessor$2);
  74142. /*
  74143. * Licensed to the Apache Software Foundation (ASF) under one
  74144. * or more contributor license agreements. See the NOTICE file
  74145. * distributed with this work for additional information
  74146. * regarding copyright ownership. The ASF licenses this file
  74147. * to you under the Apache License, Version 2.0 (the
  74148. * "License"); you may not use this file except in compliance
  74149. * with the License. You may obtain a copy of the License at
  74150. *
  74151. * http://www.apache.org/licenses/LICENSE-2.0
  74152. *
  74153. * Unless required by applicable law or agreed to in writing,
  74154. * software distributed under the License is distributed on an
  74155. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74156. * KIND, either express or implied. See the License for the
  74157. * specific language governing permissions and limitations
  74158. * under the License.
  74159. */
  74160. /**
  74161. * visualMap component entry
  74162. */
  74163. /*
  74164. * Licensed to the Apache Software Foundation (ASF) under one
  74165. * or more contributor license agreements. See the NOTICE file
  74166. * distributed with this work for additional information
  74167. * regarding copyright ownership. The ASF licenses this file
  74168. * to you under the Apache License, Version 2.0 (the
  74169. * "License"); you may not use this file except in compliance
  74170. * with the License. You may obtain a copy of the License at
  74171. *
  74172. * http://www.apache.org/licenses/LICENSE-2.0
  74173. *
  74174. * Unless required by applicable law or agreed to in writing,
  74175. * software distributed under the License is distributed on an
  74176. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74177. * KIND, either express or implied. See the License for the
  74178. * specific language governing permissions and limitations
  74179. * under the License.
  74180. */
  74181. var addCommas$1 = addCommas;
  74182. var encodeHTML$1 = encodeHTML;
  74183. function fillLabel(opt) {
  74184. defaultEmphasis(opt, 'label', ['show']);
  74185. }
  74186. var MarkerModel = extendComponentModel({
  74187. type: 'marker',
  74188. dependencies: ['series', 'grid', 'polar', 'geo'],
  74189. /**
  74190. * @overrite
  74191. */
  74192. init: function (option, parentModel, ecModel, extraOpt) {
  74193. if (__DEV__) {
  74194. if (this.type === 'marker') {
  74195. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  74196. }
  74197. }
  74198. this.mergeDefaultAndTheme(option, ecModel);
  74199. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  74200. },
  74201. /**
  74202. * @return {boolean}
  74203. */
  74204. isAnimationEnabled: function () {
  74205. if (env$1.node) {
  74206. return false;
  74207. }
  74208. var hostSeries = this.__hostSeries;
  74209. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  74210. },
  74211. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  74212. var MarkerModel = this.constructor;
  74213. var modelPropName = this.mainType + 'Model';
  74214. if (!createdBySelf) {
  74215. ecModel.eachSeries(function (seriesModel) {
  74216. var markerOpt = seriesModel.get(this.mainType, true);
  74217. var markerModel = seriesModel[modelPropName];
  74218. if (!markerOpt || !markerOpt.data) {
  74219. seriesModel[modelPropName] = null;
  74220. return;
  74221. }
  74222. if (!markerModel) {
  74223. if (isInit) {
  74224. // Default label emphasis `position` and `show`
  74225. fillLabel(markerOpt);
  74226. }
  74227. each$1(markerOpt.data, function (item) {
  74228. // FIXME Overwrite fillLabel method ?
  74229. if (item instanceof Array) {
  74230. fillLabel(item[0]);
  74231. fillLabel(item[1]);
  74232. }
  74233. else {
  74234. fillLabel(item);
  74235. }
  74236. });
  74237. markerModel = new MarkerModel(
  74238. markerOpt, this, ecModel
  74239. );
  74240. extend(markerModel, {
  74241. mainType: this.mainType,
  74242. // Use the same series index and name
  74243. seriesIndex: seriesModel.seriesIndex,
  74244. name: seriesModel.name,
  74245. createdBySelf: true
  74246. });
  74247. markerModel.__hostSeries = seriesModel;
  74248. }
  74249. else {
  74250. markerModel.mergeOption(markerOpt, ecModel, true);
  74251. }
  74252. seriesModel[modelPropName] = markerModel;
  74253. }, this);
  74254. }
  74255. },
  74256. formatTooltip: function (dataIndex) {
  74257. var data = this.getData();
  74258. var value = this.getRawValue(dataIndex);
  74259. var formattedValue = isArray(value)
  74260. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  74261. var name = data.getName(dataIndex);
  74262. var html = encodeHTML$1(this.name);
  74263. if (value != null || name) {
  74264. html += '<br />';
  74265. }
  74266. if (name) {
  74267. html += encodeHTML$1(name);
  74268. if (value != null) {
  74269. html += ' : ';
  74270. }
  74271. }
  74272. if (value != null) {
  74273. html += encodeHTML$1(formattedValue);
  74274. }
  74275. return html;
  74276. },
  74277. getData: function () {
  74278. return this._data;
  74279. },
  74280. setData: function (data) {
  74281. this._data = data;
  74282. }
  74283. });
  74284. mixin(MarkerModel, dataFormatMixin);
  74285. /*
  74286. * Licensed to the Apache Software Foundation (ASF) under one
  74287. * or more contributor license agreements. See the NOTICE file
  74288. * distributed with this work for additional information
  74289. * regarding copyright ownership. The ASF licenses this file
  74290. * to you under the Apache License, Version 2.0 (the
  74291. * "License"); you may not use this file except in compliance
  74292. * with the License. You may obtain a copy of the License at
  74293. *
  74294. * http://www.apache.org/licenses/LICENSE-2.0
  74295. *
  74296. * Unless required by applicable law or agreed to in writing,
  74297. * software distributed under the License is distributed on an
  74298. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74299. * KIND, either express or implied. See the License for the
  74300. * specific language governing permissions and limitations
  74301. * under the License.
  74302. */
  74303. MarkerModel.extend({
  74304. type: 'markPoint',
  74305. defaultOption: {
  74306. zlevel: 0,
  74307. z: 5,
  74308. symbol: 'pin',
  74309. symbolSize: 50,
  74310. //symbolRotate: 0,
  74311. //symbolOffset: [0, 0]
  74312. tooltip: {
  74313. trigger: 'item'
  74314. },
  74315. label: {
  74316. show: true,
  74317. position: 'inside'
  74318. },
  74319. itemStyle: {
  74320. borderWidth: 2
  74321. },
  74322. emphasis: {
  74323. label: {
  74324. show: true
  74325. }
  74326. }
  74327. }
  74328. });
  74329. /*
  74330. * Licensed to the Apache Software Foundation (ASF) under one
  74331. * or more contributor license agreements. See the NOTICE file
  74332. * distributed with this work for additional information
  74333. * regarding copyright ownership. The ASF licenses this file
  74334. * to you under the Apache License, Version 2.0 (the
  74335. * "License"); you may not use this file except in compliance
  74336. * with the License. You may obtain a copy of the License at
  74337. *
  74338. * http://www.apache.org/licenses/LICENSE-2.0
  74339. *
  74340. * Unless required by applicable law or agreed to in writing,
  74341. * software distributed under the License is distributed on an
  74342. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74343. * KIND, either express or implied. See the License for the
  74344. * specific language governing permissions and limitations
  74345. * under the License.
  74346. */
  74347. var indexOf$2 = indexOf;
  74348. function hasXOrY(item) {
  74349. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  74350. }
  74351. function hasXAndY(item) {
  74352. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  74353. }
  74354. // Make it simple, do not visit all stacked value to count precision.
  74355. // function getPrecision(data, valueAxisDim, dataIndex) {
  74356. // var precision = -1;
  74357. // var stackedDim = data.mapDimension(valueAxisDim);
  74358. // do {
  74359. // precision = Math.max(
  74360. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  74361. // precision
  74362. // );
  74363. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  74364. // if (stackedOnSeries) {
  74365. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  74366. // data = stackedOnSeries.getData();
  74367. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  74368. // stackedDim = data.getCalculationInfo('stackedDimension');
  74369. // }
  74370. // else {
  74371. // data = null;
  74372. // }
  74373. // } while (data);
  74374. // return precision;
  74375. // }
  74376. function markerTypeCalculatorWithExtent(
  74377. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  74378. ) {
  74379. var coordArr = [];
  74380. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  74381. var calcDataDim = stacked
  74382. ? data.getCalculationInfo('stackResultDimension')
  74383. : targetDataDim;
  74384. var value = numCalculate(data, calcDataDim, mlType);
  74385. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  74386. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  74387. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  74388. // Make it simple, do not visit all stacked value to count precision.
  74389. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  74390. precision = Math.min(precision, 20);
  74391. if (precision >= 0) {
  74392. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  74393. }
  74394. return coordArr;
  74395. }
  74396. var curry$6 = curry;
  74397. // TODO Specified percent
  74398. var markerTypeCalculator = {
  74399. /**
  74400. * @method
  74401. * @param {module:echarts/data/List} data
  74402. * @param {string} baseAxisDim
  74403. * @param {string} valueAxisDim
  74404. */
  74405. min: curry$6(markerTypeCalculatorWithExtent, 'min'),
  74406. /**
  74407. * @method
  74408. * @param {module:echarts/data/List} data
  74409. * @param {string} baseAxisDim
  74410. * @param {string} valueAxisDim
  74411. */
  74412. max: curry$6(markerTypeCalculatorWithExtent, 'max'),
  74413. /**
  74414. * @method
  74415. * @param {module:echarts/data/List} data
  74416. * @param {string} baseAxisDim
  74417. * @param {string} valueAxisDim
  74418. */
  74419. average: curry$6(markerTypeCalculatorWithExtent, 'average')
  74420. };
  74421. /**
  74422. * Transform markPoint data item to format used in List by do the following
  74423. * 1. Calculate statistic like `max`, `min`, `average`
  74424. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  74425. * @param {module:echarts/model/Series} seriesModel
  74426. * @param {module:echarts/coord/*} [coordSys]
  74427. * @param {Object} item
  74428. * @return {Object}
  74429. */
  74430. function dataTransform(seriesModel, item) {
  74431. var data = seriesModel.getData();
  74432. var coordSys = seriesModel.coordinateSystem;
  74433. // 1. If not specify the position with pixel directly
  74434. // 2. If `coord` is not a data array. Which uses `xAxis`,
  74435. // `yAxis` to specify the coord on each dimension
  74436. // parseFloat first because item.x and item.y can be percent string like '20%'
  74437. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  74438. var dims = coordSys.dimensions;
  74439. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  74440. // Clone the option
  74441. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  74442. item = clone(item);
  74443. if (item.type
  74444. && markerTypeCalculator[item.type]
  74445. && axisInfo.baseAxis && axisInfo.valueAxis
  74446. ) {
  74447. var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim);
  74448. var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim);
  74449. item.coord = markerTypeCalculator[item.type](
  74450. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  74451. otherCoordIndex, targetCoordIndex
  74452. );
  74453. // Force to use the value of calculated value.
  74454. item.value = item.coord[targetCoordIndex];
  74455. }
  74456. else {
  74457. // FIXME Only has one of xAxis and yAxis.
  74458. var coord = [
  74459. item.xAxis != null ? item.xAxis : item.radiusAxis,
  74460. item.yAxis != null ? item.yAxis : item.angleAxis
  74461. ];
  74462. // Each coord support max, min, average
  74463. for (var i = 0; i < 2; i++) {
  74464. if (markerTypeCalculator[coord[i]]) {
  74465. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  74466. }
  74467. }
  74468. item.coord = coord;
  74469. }
  74470. }
  74471. return item;
  74472. }
  74473. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  74474. var ret = {};
  74475. if (item.valueIndex != null || item.valueDim != null) {
  74476. ret.valueDataDim = item.valueIndex != null
  74477. ? data.getDimension(item.valueIndex) : item.valueDim;
  74478. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  74479. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  74480. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74481. }
  74482. else {
  74483. ret.baseAxis = seriesModel.getBaseAxis();
  74484. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  74485. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74486. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  74487. }
  74488. return ret;
  74489. }
  74490. function dataDimToCoordDim(seriesModel, dataDim) {
  74491. var data = seriesModel.getData();
  74492. var dimensions = data.dimensions;
  74493. dataDim = data.getDimension(dataDim);
  74494. for (var i = 0; i < dimensions.length; i++) {
  74495. var dimItem = data.getDimensionInfo(dimensions[i]);
  74496. if (dimItem.name === dataDim) {
  74497. return dimItem.coordDim;
  74498. }
  74499. }
  74500. }
  74501. /**
  74502. * Filter data which is out of coordinateSystem range
  74503. * [dataFilter description]
  74504. * @param {module:echarts/coord/*} [coordSys]
  74505. * @param {Object} item
  74506. * @return {boolean}
  74507. */
  74508. function dataFilter$1(coordSys, item) {
  74509. // Alwalys return true if there is no coordSys
  74510. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  74511. ? coordSys.containData(item.coord) : true;
  74512. }
  74513. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  74514. // x, y, radius, angle
  74515. if (dimIndex < 2) {
  74516. return item.coord && item.coord[dimIndex];
  74517. }
  74518. return item.value;
  74519. }
  74520. function numCalculate(data, valueDataDim, type) {
  74521. if (type === 'average') {
  74522. var sum = 0;
  74523. var count = 0;
  74524. data.each(valueDataDim, function (val, idx) {
  74525. if (!isNaN(val)) {
  74526. sum += val;
  74527. count++;
  74528. }
  74529. });
  74530. return sum / count;
  74531. }
  74532. else if (type === 'median') {
  74533. return data.getMedian(valueDataDim);
  74534. }
  74535. else {
  74536. // max & min
  74537. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  74538. }
  74539. }
  74540. /*
  74541. * Licensed to the Apache Software Foundation (ASF) under one
  74542. * or more contributor license agreements. See the NOTICE file
  74543. * distributed with this work for additional information
  74544. * regarding copyright ownership. The ASF licenses this file
  74545. * to you under the Apache License, Version 2.0 (the
  74546. * "License"); you may not use this file except in compliance
  74547. * with the License. You may obtain a copy of the License at
  74548. *
  74549. * http://www.apache.org/licenses/LICENSE-2.0
  74550. *
  74551. * Unless required by applicable law or agreed to in writing,
  74552. * software distributed under the License is distributed on an
  74553. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74554. * KIND, either express or implied. See the License for the
  74555. * specific language governing permissions and limitations
  74556. * under the License.
  74557. */
  74558. var MarkerView = extendComponentView({
  74559. type: 'marker',
  74560. init: function () {
  74561. /**
  74562. * Markline grouped by series
  74563. * @private
  74564. * @type {module:zrender/core/util.HashMap}
  74565. */
  74566. this.markerGroupMap = createHashMap();
  74567. },
  74568. render: function (markerModel, ecModel, api) {
  74569. var markerGroupMap = this.markerGroupMap;
  74570. markerGroupMap.each(function (item) {
  74571. item.__keep = false;
  74572. });
  74573. var markerModelKey = this.type + 'Model';
  74574. ecModel.eachSeries(function (seriesModel) {
  74575. var markerModel = seriesModel[markerModelKey];
  74576. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  74577. }, this);
  74578. markerGroupMap.each(function (item) {
  74579. !item.__keep && this.group.remove(item.group);
  74580. }, this);
  74581. },
  74582. renderSeries: function () {}
  74583. });
  74584. /*
  74585. * Licensed to the Apache Software Foundation (ASF) under one
  74586. * or more contributor license agreements. See the NOTICE file
  74587. * distributed with this work for additional information
  74588. * regarding copyright ownership. The ASF licenses this file
  74589. * to you under the Apache License, Version 2.0 (the
  74590. * "License"); you may not use this file except in compliance
  74591. * with the License. You may obtain a copy of the License at
  74592. *
  74593. * http://www.apache.org/licenses/LICENSE-2.0
  74594. *
  74595. * Unless required by applicable law or agreed to in writing,
  74596. * software distributed under the License is distributed on an
  74597. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74598. * KIND, either express or implied. See the License for the
  74599. * specific language governing permissions and limitations
  74600. * under the License.
  74601. */
  74602. function updateMarkerLayout(mpData, seriesModel, api) {
  74603. var coordSys = seriesModel.coordinateSystem;
  74604. mpData.each(function (idx) {
  74605. var itemModel = mpData.getItemModel(idx);
  74606. var point;
  74607. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  74608. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  74609. if (!isNaN(xPx) && !isNaN(yPx)) {
  74610. point = [xPx, yPx];
  74611. }
  74612. // Chart like bar may have there own marker positioning logic
  74613. else if (seriesModel.getMarkerPosition) {
  74614. // Use the getMarkerPoisition
  74615. point = seriesModel.getMarkerPosition(
  74616. mpData.getValues(mpData.dimensions, idx)
  74617. );
  74618. }
  74619. else if (coordSys) {
  74620. var x = mpData.get(coordSys.dimensions[0], idx);
  74621. var y = mpData.get(coordSys.dimensions[1], idx);
  74622. point = coordSys.dataToPoint([x, y]);
  74623. }
  74624. // Use x, y if has any
  74625. if (!isNaN(xPx)) {
  74626. point[0] = xPx;
  74627. }
  74628. if (!isNaN(yPx)) {
  74629. point[1] = yPx;
  74630. }
  74631. mpData.setItemLayout(idx, point);
  74632. });
  74633. }
  74634. MarkerView.extend({
  74635. type: 'markPoint',
  74636. // updateLayout: function (markPointModel, ecModel, api) {
  74637. // ecModel.eachSeries(function (seriesModel) {
  74638. // var mpModel = seriesModel.markPointModel;
  74639. // if (mpModel) {
  74640. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74641. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  74642. // }
  74643. // }, this);
  74644. // },
  74645. updateTransform: function (markPointModel, ecModel, api) {
  74646. ecModel.eachSeries(function (seriesModel) {
  74647. var mpModel = seriesModel.markPointModel;
  74648. if (mpModel) {
  74649. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74650. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  74651. }
  74652. }, this);
  74653. },
  74654. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  74655. var coordSys = seriesModel.coordinateSystem;
  74656. var seriesId = seriesModel.id;
  74657. var seriesData = seriesModel.getData();
  74658. var symbolDrawMap = this.markerGroupMap;
  74659. var symbolDraw = symbolDrawMap.get(seriesId)
  74660. || symbolDrawMap.set(seriesId, new SymbolDraw());
  74661. var mpData = createList$1(coordSys, seriesModel, mpModel);
  74662. // FIXME
  74663. mpModel.setData(mpData);
  74664. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74665. mpData.each(function (idx) {
  74666. var itemModel = mpData.getItemModel(idx);
  74667. var symbolSize = itemModel.getShallow('symbolSize');
  74668. if (typeof symbolSize === 'function') {
  74669. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  74670. symbolSize = symbolSize(
  74671. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  74672. );
  74673. }
  74674. mpData.setItemVisual(idx, {
  74675. symbolSize: symbolSize,
  74676. color: itemModel.get('itemStyle.color')
  74677. || seriesData.getVisual('color'),
  74678. symbol: itemModel.getShallow('symbol')
  74679. });
  74680. });
  74681. // TODO Text are wrong
  74682. symbolDraw.updateData(mpData);
  74683. this.group.add(symbolDraw.group);
  74684. // Set host model for tooltip
  74685. // FIXME
  74686. mpData.eachItemGraphicEl(function (el) {
  74687. el.traverse(function (child) {
  74688. child.dataModel = mpModel;
  74689. });
  74690. });
  74691. symbolDraw.__keep = true;
  74692. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  74693. }
  74694. });
  74695. /**
  74696. * @inner
  74697. * @param {module:echarts/coord/*} [coordSys]
  74698. * @param {module:echarts/model/Series} seriesModel
  74699. * @param {module:echarts/model/Model} mpModel
  74700. */
  74701. function createList$1(coordSys, seriesModel, mpModel) {
  74702. var coordDimsInfos;
  74703. if (coordSys) {
  74704. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  74705. var info = seriesModel.getData().getDimensionInfo(
  74706. seriesModel.getData().mapDimension(coordDim)
  74707. ) || {};
  74708. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  74709. return defaults({name: coordDim}, info);
  74710. });
  74711. }
  74712. else {
  74713. coordDimsInfos = [{
  74714. name: 'value',
  74715. type: 'float'
  74716. }];
  74717. }
  74718. var mpData = new List(coordDimsInfos, mpModel);
  74719. var dataOpt = map(mpModel.get('data'), curry(
  74720. dataTransform, seriesModel
  74721. ));
  74722. if (coordSys) {
  74723. dataOpt = filter(
  74724. dataOpt, curry(dataFilter$1, coordSys)
  74725. );
  74726. }
  74727. mpData.initData(dataOpt, null,
  74728. coordSys ? dimValueGetter : function (item) {
  74729. return item.value;
  74730. }
  74731. );
  74732. return mpData;
  74733. }
  74734. /*
  74735. * Licensed to the Apache Software Foundation (ASF) under one
  74736. * or more contributor license agreements. See the NOTICE file
  74737. * distributed with this work for additional information
  74738. * regarding copyright ownership. The ASF licenses this file
  74739. * to you under the Apache License, Version 2.0 (the
  74740. * "License"); you may not use this file except in compliance
  74741. * with the License. You may obtain a copy of the License at
  74742. *
  74743. * http://www.apache.org/licenses/LICENSE-2.0
  74744. *
  74745. * Unless required by applicable law or agreed to in writing,
  74746. * software distributed under the License is distributed on an
  74747. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74748. * KIND, either express or implied. See the License for the
  74749. * specific language governing permissions and limitations
  74750. * under the License.
  74751. */
  74752. // HINT Markpoint can't be used too much
  74753. registerPreprocessor(function (opt) {
  74754. // Make sure markPoint component is enabled
  74755. opt.markPoint = opt.markPoint || {};
  74756. });
  74757. /*
  74758. * Licensed to the Apache Software Foundation (ASF) under one
  74759. * or more contributor license agreements. See the NOTICE file
  74760. * distributed with this work for additional information
  74761. * regarding copyright ownership. The ASF licenses this file
  74762. * to you under the Apache License, Version 2.0 (the
  74763. * "License"); you may not use this file except in compliance
  74764. * with the License. You may obtain a copy of the License at
  74765. *
  74766. * http://www.apache.org/licenses/LICENSE-2.0
  74767. *
  74768. * Unless required by applicable law or agreed to in writing,
  74769. * software distributed under the License is distributed on an
  74770. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74771. * KIND, either express or implied. See the License for the
  74772. * specific language governing permissions and limitations
  74773. * under the License.
  74774. */
  74775. MarkerModel.extend({
  74776. type: 'markLine',
  74777. defaultOption: {
  74778. zlevel: 0,
  74779. z: 5,
  74780. symbol: ['circle', 'arrow'],
  74781. symbolSize: [8, 16],
  74782. //symbolRotate: 0,
  74783. precision: 2,
  74784. tooltip: {
  74785. trigger: 'item'
  74786. },
  74787. label: {
  74788. show: true,
  74789. position: 'end'
  74790. },
  74791. lineStyle: {
  74792. type: 'dashed'
  74793. },
  74794. emphasis: {
  74795. label: {
  74796. show: true
  74797. },
  74798. lineStyle: {
  74799. width: 3
  74800. }
  74801. },
  74802. animationEasing: 'linear'
  74803. }
  74804. });
  74805. /*
  74806. * Licensed to the Apache Software Foundation (ASF) under one
  74807. * or more contributor license agreements. See the NOTICE file
  74808. * distributed with this work for additional information
  74809. * regarding copyright ownership. The ASF licenses this file
  74810. * to you under the Apache License, Version 2.0 (the
  74811. * "License"); you may not use this file except in compliance
  74812. * with the License. You may obtain a copy of the License at
  74813. *
  74814. * http://www.apache.org/licenses/LICENSE-2.0
  74815. *
  74816. * Unless required by applicable law or agreed to in writing,
  74817. * software distributed under the License is distributed on an
  74818. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74819. * KIND, either express or implied. See the License for the
  74820. * specific language governing permissions and limitations
  74821. * under the License.
  74822. */
  74823. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  74824. var data = seriesModel.getData();
  74825. // Special type markLine like 'min', 'max', 'average', 'median'
  74826. var mlType = item.type;
  74827. if (!isArray(item)
  74828. && (
  74829. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  74830. // In case
  74831. // data: [{
  74832. // yAxis: 10
  74833. // }]
  74834. || (item.xAxis != null || item.yAxis != null)
  74835. )
  74836. ) {
  74837. var valueAxis;
  74838. var valueDataDim;
  74839. var value;
  74840. if (item.yAxis != null || item.xAxis != null) {
  74841. valueDataDim = item.yAxis != null ? 'y' : 'x';
  74842. valueAxis = coordSys.getAxis(valueDataDim);
  74843. value = retrieve(item.yAxis, item.xAxis);
  74844. }
  74845. else {
  74846. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  74847. valueDataDim = axisInfo.valueDataDim;
  74848. valueAxis = axisInfo.valueAxis;
  74849. value = numCalculate(data, valueDataDim, mlType);
  74850. }
  74851. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  74852. var baseIndex = 1 - valueIndex;
  74853. var mlFrom = clone(item);
  74854. var mlTo = {};
  74855. mlFrom.type = null;
  74856. mlFrom.coord = [];
  74857. mlTo.coord = [];
  74858. mlFrom.coord[baseIndex] = -Infinity;
  74859. mlTo.coord[baseIndex] = Infinity;
  74860. var precision = mlModel.get('precision');
  74861. if (precision >= 0 && typeof value === 'number') {
  74862. value = +value.toFixed(Math.min(precision, 20));
  74863. }
  74864. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  74865. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  74866. type: mlType,
  74867. valueIndex: item.valueIndex,
  74868. // Force to use the value of calculated value.
  74869. value: value
  74870. }];
  74871. }
  74872. item = [
  74873. dataTransform(seriesModel, item[0]),
  74874. dataTransform(seriesModel, item[1]),
  74875. extend({}, item[2])
  74876. ];
  74877. // Avoid line data type is extended by from(to) data type
  74878. item[2].type = item[2].type || '';
  74879. // Merge from option and to option into line option
  74880. merge(item[2], item[0]);
  74881. merge(item[2], item[1]);
  74882. return item;
  74883. };
  74884. function isInifinity(val) {
  74885. return !isNaN(val) && !isFinite(val);
  74886. }
  74887. // If a markLine has one dim
  74888. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  74889. var otherDimIndex = 1 - dimIndex;
  74890. var dimName = coordSys.dimensions[dimIndex];
  74891. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  74892. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  74893. }
  74894. function markLineFilter(coordSys, item) {
  74895. if (coordSys.type === 'cartesian2d') {
  74896. var fromCoord = item[0].coord;
  74897. var toCoord = item[1].coord;
  74898. // In case
  74899. // {
  74900. // markLine: {
  74901. // data: [{ yAxis: 2 }]
  74902. // }
  74903. // }
  74904. if (
  74905. fromCoord && toCoord
  74906. && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  74907. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  74908. ) {
  74909. return true;
  74910. }
  74911. }
  74912. return dataFilter$1(coordSys, item[0])
  74913. && dataFilter$1(coordSys, item[1]);
  74914. }
  74915. function updateSingleMarkerEndLayout(
  74916. data, idx, isFrom, seriesModel, api
  74917. ) {
  74918. var coordSys = seriesModel.coordinateSystem;
  74919. var itemModel = data.getItemModel(idx);
  74920. var point;
  74921. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  74922. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  74923. if (!isNaN(xPx) && !isNaN(yPx)) {
  74924. point = [xPx, yPx];
  74925. }
  74926. else {
  74927. // Chart like bar may have there own marker positioning logic
  74928. if (seriesModel.getMarkerPosition) {
  74929. // Use the getMarkerPoisition
  74930. point = seriesModel.getMarkerPosition(
  74931. data.getValues(data.dimensions, idx)
  74932. );
  74933. }
  74934. else {
  74935. var dims = coordSys.dimensions;
  74936. var x = data.get(dims[0], idx);
  74937. var y = data.get(dims[1], idx);
  74938. point = coordSys.dataToPoint([x, y]);
  74939. }
  74940. // Expand line to the edge of grid if value on one axis is Inifnity
  74941. // In case
  74942. // markLine: {
  74943. // data: [{
  74944. // yAxis: 2
  74945. // // or
  74946. // type: 'average'
  74947. // }]
  74948. // }
  74949. if (coordSys.type === 'cartesian2d') {
  74950. var xAxis = coordSys.getAxis('x');
  74951. var yAxis = coordSys.getAxis('y');
  74952. var dims = coordSys.dimensions;
  74953. if (isInifinity(data.get(dims[0], idx))) {
  74954. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  74955. }
  74956. else if (isInifinity(data.get(dims[1], idx))) {
  74957. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  74958. }
  74959. }
  74960. // Use x, y if has any
  74961. if (!isNaN(xPx)) {
  74962. point[0] = xPx;
  74963. }
  74964. if (!isNaN(yPx)) {
  74965. point[1] = yPx;
  74966. }
  74967. }
  74968. data.setItemLayout(idx, point);
  74969. }
  74970. MarkerView.extend({
  74971. type: 'markLine',
  74972. // updateLayout: function (markLineModel, ecModel, api) {
  74973. // ecModel.eachSeries(function (seriesModel) {
  74974. // var mlModel = seriesModel.markLineModel;
  74975. // if (mlModel) {
  74976. // var mlData = mlModel.getData();
  74977. // var fromData = mlModel.__from;
  74978. // var toData = mlModel.__to;
  74979. // // Update visual and layout of from symbol and to symbol
  74980. // fromData.each(function (idx) {
  74981. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  74982. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  74983. // });
  74984. // // Update layout of line
  74985. // mlData.each(function (idx) {
  74986. // mlData.setItemLayout(idx, [
  74987. // fromData.getItemLayout(idx),
  74988. // toData.getItemLayout(idx)
  74989. // ]);
  74990. // });
  74991. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  74992. // }
  74993. // }, this);
  74994. // },
  74995. updateTransform: function (markLineModel, ecModel, api) {
  74996. ecModel.eachSeries(function (seriesModel) {
  74997. var mlModel = seriesModel.markLineModel;
  74998. if (mlModel) {
  74999. var mlData = mlModel.getData();
  75000. var fromData = mlModel.__from;
  75001. var toData = mlModel.__to;
  75002. // Update visual and layout of from symbol and to symbol
  75003. fromData.each(function (idx) {
  75004. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  75005. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  75006. });
  75007. // Update layout of line
  75008. mlData.each(function (idx) {
  75009. mlData.setItemLayout(idx, [
  75010. fromData.getItemLayout(idx),
  75011. toData.getItemLayout(idx)
  75012. ]);
  75013. });
  75014. this.markerGroupMap.get(seriesModel.id).updateLayout();
  75015. }
  75016. }, this);
  75017. },
  75018. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  75019. var coordSys = seriesModel.coordinateSystem;
  75020. var seriesId = seriesModel.id;
  75021. var seriesData = seriesModel.getData();
  75022. var lineDrawMap = this.markerGroupMap;
  75023. var lineDraw = lineDrawMap.get(seriesId)
  75024. || lineDrawMap.set(seriesId, new LineDraw());
  75025. this.group.add(lineDraw.group);
  75026. var mlData = createList$2(coordSys, seriesModel, mlModel);
  75027. var fromData = mlData.from;
  75028. var toData = mlData.to;
  75029. var lineData = mlData.line;
  75030. mlModel.__from = fromData;
  75031. mlModel.__to = toData;
  75032. // Line data for tooltip and formatter
  75033. mlModel.setData(lineData);
  75034. var symbolType = mlModel.get('symbol');
  75035. var symbolSize = mlModel.get('symbolSize');
  75036. if (!isArray(symbolType)) {
  75037. symbolType = [symbolType, symbolType];
  75038. }
  75039. if (typeof symbolSize === 'number') {
  75040. symbolSize = [symbolSize, symbolSize];
  75041. }
  75042. // Update visual and layout of from symbol and to symbol
  75043. mlData.from.each(function (idx) {
  75044. updateDataVisualAndLayout(fromData, idx, true);
  75045. updateDataVisualAndLayout(toData, idx, false);
  75046. });
  75047. // Update visual and layout of line
  75048. lineData.each(function (idx) {
  75049. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  75050. lineData.setItemVisual(idx, {
  75051. color: lineColor || fromData.getItemVisual(idx, 'color')
  75052. });
  75053. lineData.setItemLayout(idx, [
  75054. fromData.getItemLayout(idx),
  75055. toData.getItemLayout(idx)
  75056. ]);
  75057. lineData.setItemVisual(idx, {
  75058. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  75059. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  75060. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  75061. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  75062. });
  75063. });
  75064. lineDraw.updateData(lineData);
  75065. // Set host model for tooltip
  75066. // FIXME
  75067. mlData.line.eachItemGraphicEl(function (el, idx) {
  75068. el.traverse(function (child) {
  75069. child.dataModel = mlModel;
  75070. });
  75071. });
  75072. function updateDataVisualAndLayout(data, idx, isFrom) {
  75073. var itemModel = data.getItemModel(idx);
  75074. updateSingleMarkerEndLayout(
  75075. data, idx, isFrom, seriesModel, api
  75076. );
  75077. data.setItemVisual(idx, {
  75078. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  75079. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  75080. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  75081. });
  75082. }
  75083. lineDraw.__keep = true;
  75084. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  75085. }
  75086. });
  75087. /**
  75088. * @inner
  75089. * @param {module:echarts/coord/*} coordSys
  75090. * @param {module:echarts/model/Series} seriesModel
  75091. * @param {module:echarts/model/Model} mpModel
  75092. */
  75093. function createList$2(coordSys, seriesModel, mlModel) {
  75094. var coordDimsInfos;
  75095. if (coordSys) {
  75096. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75097. var info = seriesModel.getData().getDimensionInfo(
  75098. seriesModel.getData().mapDimension(coordDim)
  75099. ) || {};
  75100. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75101. return defaults({name: coordDim}, info);
  75102. });
  75103. }
  75104. else {
  75105. coordDimsInfos = [{
  75106. name: 'value',
  75107. type: 'float'
  75108. }];
  75109. }
  75110. var fromData = new List(coordDimsInfos, mlModel);
  75111. var toData = new List(coordDimsInfos, mlModel);
  75112. // No dimensions
  75113. var lineData = new List([], mlModel);
  75114. var optData = map(mlModel.get('data'), curry(
  75115. markLineTransform, seriesModel, coordSys, mlModel
  75116. ));
  75117. if (coordSys) {
  75118. optData = filter(
  75119. optData, curry(markLineFilter, coordSys)
  75120. );
  75121. }
  75122. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  75123. return item.value;
  75124. };
  75125. fromData.initData(
  75126. map(optData, function (item) {
  75127. return item[0];
  75128. }),
  75129. null,
  75130. dimValueGetter$$1
  75131. );
  75132. toData.initData(
  75133. map(optData, function (item) {
  75134. return item[1];
  75135. }),
  75136. null,
  75137. dimValueGetter$$1
  75138. );
  75139. lineData.initData(
  75140. map(optData, function (item) {
  75141. return item[2];
  75142. })
  75143. );
  75144. lineData.hasItemOption = true;
  75145. return {
  75146. from: fromData,
  75147. to: toData,
  75148. line: lineData
  75149. };
  75150. }
  75151. /*
  75152. * Licensed to the Apache Software Foundation (ASF) under one
  75153. * or more contributor license agreements. See the NOTICE file
  75154. * distributed with this work for additional information
  75155. * regarding copyright ownership. The ASF licenses this file
  75156. * to you under the Apache License, Version 2.0 (the
  75157. * "License"); you may not use this file except in compliance
  75158. * with the License. You may obtain a copy of the License at
  75159. *
  75160. * http://www.apache.org/licenses/LICENSE-2.0
  75161. *
  75162. * Unless required by applicable law or agreed to in writing,
  75163. * software distributed under the License is distributed on an
  75164. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75165. * KIND, either express or implied. See the License for the
  75166. * specific language governing permissions and limitations
  75167. * under the License.
  75168. */
  75169. registerPreprocessor(function (opt) {
  75170. // Make sure markLine component is enabled
  75171. opt.markLine = opt.markLine || {};
  75172. });
  75173. /*
  75174. * Licensed to the Apache Software Foundation (ASF) under one
  75175. * or more contributor license agreements. See the NOTICE file
  75176. * distributed with this work for additional information
  75177. * regarding copyright ownership. The ASF licenses this file
  75178. * to you under the Apache License, Version 2.0 (the
  75179. * "License"); you may not use this file except in compliance
  75180. * with the License. You may obtain a copy of the License at
  75181. *
  75182. * http://www.apache.org/licenses/LICENSE-2.0
  75183. *
  75184. * Unless required by applicable law or agreed to in writing,
  75185. * software distributed under the License is distributed on an
  75186. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75187. * KIND, either express or implied. See the License for the
  75188. * specific language governing permissions and limitations
  75189. * under the License.
  75190. */
  75191. MarkerModel.extend({
  75192. type: 'markArea',
  75193. defaultOption: {
  75194. zlevel: 0,
  75195. // PENDING
  75196. z: 1,
  75197. tooltip: {
  75198. trigger: 'item'
  75199. },
  75200. // markArea should fixed on the coordinate system
  75201. animation: false,
  75202. label: {
  75203. show: true,
  75204. position: 'top'
  75205. },
  75206. itemStyle: {
  75207. // color and borderColor default to use color from series
  75208. // color: 'auto'
  75209. // borderColor: 'auto'
  75210. borderWidth: 0
  75211. },
  75212. emphasis: {
  75213. label: {
  75214. show: true,
  75215. position: 'top'
  75216. }
  75217. }
  75218. }
  75219. });
  75220. /*
  75221. * Licensed to the Apache Software Foundation (ASF) under one
  75222. * or more contributor license agreements. See the NOTICE file
  75223. * distributed with this work for additional information
  75224. * regarding copyright ownership. The ASF licenses this file
  75225. * to you under the Apache License, Version 2.0 (the
  75226. * "License"); you may not use this file except in compliance
  75227. * with the License. You may obtain a copy of the License at
  75228. *
  75229. * http://www.apache.org/licenses/LICENSE-2.0
  75230. *
  75231. * Unless required by applicable law or agreed to in writing,
  75232. * software distributed under the License is distributed on an
  75233. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75234. * KIND, either express or implied. See the License for the
  75235. * specific language governing permissions and limitations
  75236. * under the License.
  75237. */
  75238. // TODO Better on polar
  75239. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  75240. var lt = dataTransform(seriesModel, item[0]);
  75241. var rb = dataTransform(seriesModel, item[1]);
  75242. var retrieve$$1 = retrieve;
  75243. // FIXME make sure lt is less than rb
  75244. var ltCoord = lt.coord;
  75245. var rbCoord = rb.coord;
  75246. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  75247. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  75248. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  75249. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  75250. // Merge option into one
  75251. var result = mergeAll([{}, lt, rb]);
  75252. result.coord = [
  75253. lt.coord, rb.coord
  75254. ];
  75255. result.x0 = lt.x;
  75256. result.y0 = lt.y;
  75257. result.x1 = rb.x;
  75258. result.y1 = rb.y;
  75259. return result;
  75260. };
  75261. function isInifinity$1(val) {
  75262. return !isNaN(val) && !isFinite(val);
  75263. }
  75264. // If a markArea has one dim
  75265. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  75266. var otherDimIndex = 1 - dimIndex;
  75267. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  75268. }
  75269. function markAreaFilter(coordSys, item) {
  75270. var fromCoord = item.coord[0];
  75271. var toCoord = item.coord[1];
  75272. if (coordSys.type === 'cartesian2d') {
  75273. // In case
  75274. // {
  75275. // markArea: {
  75276. // data: [{ yAxis: 2 }]
  75277. // }
  75278. // }
  75279. if (
  75280. fromCoord && toCoord
  75281. && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  75282. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  75283. ) {
  75284. return true;
  75285. }
  75286. }
  75287. return dataFilter$1(coordSys, {
  75288. coord: fromCoord,
  75289. x: item.x0,
  75290. y: item.y0
  75291. })
  75292. || dataFilter$1(coordSys, {
  75293. coord: toCoord,
  75294. x: item.x1,
  75295. y: item.y1
  75296. });
  75297. }
  75298. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  75299. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  75300. var coordSys = seriesModel.coordinateSystem;
  75301. var itemModel = data.getItemModel(idx);
  75302. var point;
  75303. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  75304. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  75305. if (!isNaN(xPx) && !isNaN(yPx)) {
  75306. point = [xPx, yPx];
  75307. }
  75308. else {
  75309. // Chart like bar may have there own marker positioning logic
  75310. if (seriesModel.getMarkerPosition) {
  75311. // Use the getMarkerPoisition
  75312. point = seriesModel.getMarkerPosition(
  75313. data.getValues(dims, idx)
  75314. );
  75315. }
  75316. else {
  75317. var x = data.get(dims[0], idx);
  75318. var y = data.get(dims[1], idx);
  75319. var pt = [x, y];
  75320. coordSys.clampData && coordSys.clampData(pt, pt);
  75321. point = coordSys.dataToPoint(pt, true);
  75322. }
  75323. if (coordSys.type === 'cartesian2d') {
  75324. var xAxis = coordSys.getAxis('x');
  75325. var yAxis = coordSys.getAxis('y');
  75326. var x = data.get(dims[0], idx);
  75327. var y = data.get(dims[1], idx);
  75328. if (isInifinity$1(x)) {
  75329. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  75330. }
  75331. else if (isInifinity$1(y)) {
  75332. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  75333. }
  75334. }
  75335. // Use x, y if has any
  75336. if (!isNaN(xPx)) {
  75337. point[0] = xPx;
  75338. }
  75339. if (!isNaN(yPx)) {
  75340. point[1] = yPx;
  75341. }
  75342. }
  75343. return point;
  75344. }
  75345. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  75346. MarkerView.extend({
  75347. type: 'markArea',
  75348. // updateLayout: function (markAreaModel, ecModel, api) {
  75349. // ecModel.eachSeries(function (seriesModel) {
  75350. // var maModel = seriesModel.markAreaModel;
  75351. // if (maModel) {
  75352. // var areaData = maModel.getData();
  75353. // areaData.each(function (idx) {
  75354. // var points = zrUtil.map(dimPermutations, function (dim) {
  75355. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75356. // });
  75357. // // Layout
  75358. // areaData.setItemLayout(idx, points);
  75359. // var el = areaData.getItemGraphicEl(idx);
  75360. // el.setShape('points', points);
  75361. // });
  75362. // }
  75363. // }, this);
  75364. // },
  75365. updateTransform: function (markAreaModel, ecModel, api) {
  75366. ecModel.eachSeries(function (seriesModel) {
  75367. var maModel = seriesModel.markAreaModel;
  75368. if (maModel) {
  75369. var areaData = maModel.getData();
  75370. areaData.each(function (idx) {
  75371. var points = map(dimPermutations, function (dim) {
  75372. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75373. });
  75374. // Layout
  75375. areaData.setItemLayout(idx, points);
  75376. var el = areaData.getItemGraphicEl(idx);
  75377. el.setShape('points', points);
  75378. });
  75379. }
  75380. }, this);
  75381. },
  75382. renderSeries: function (seriesModel, maModel, ecModel, api) {
  75383. var coordSys = seriesModel.coordinateSystem;
  75384. var seriesId = seriesModel.id;
  75385. var seriesData = seriesModel.getData();
  75386. var areaGroupMap = this.markerGroupMap;
  75387. var polygonGroup = areaGroupMap.get(seriesId)
  75388. || areaGroupMap.set(seriesId, {group: new Group()});
  75389. this.group.add(polygonGroup.group);
  75390. polygonGroup.__keep = true;
  75391. var areaData = createList$3(coordSys, seriesModel, maModel);
  75392. // Line data for tooltip and formatter
  75393. maModel.setData(areaData);
  75394. // Update visual and layout of line
  75395. areaData.each(function (idx) {
  75396. // Layout
  75397. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  75398. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75399. }));
  75400. // Visual
  75401. areaData.setItemVisual(idx, {
  75402. color: seriesData.getVisual('color')
  75403. });
  75404. });
  75405. areaData.diff(polygonGroup.__data)
  75406. .add(function (idx) {
  75407. var polygon = new Polygon({
  75408. shape: {
  75409. points: areaData.getItemLayout(idx)
  75410. }
  75411. });
  75412. areaData.setItemGraphicEl(idx, polygon);
  75413. polygonGroup.group.add(polygon);
  75414. })
  75415. .update(function (newIdx, oldIdx) {
  75416. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  75417. updateProps(polygon, {
  75418. shape: {
  75419. points: areaData.getItemLayout(newIdx)
  75420. }
  75421. }, maModel, newIdx);
  75422. polygonGroup.group.add(polygon);
  75423. areaData.setItemGraphicEl(newIdx, polygon);
  75424. })
  75425. .remove(function (idx) {
  75426. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  75427. polygonGroup.group.remove(polygon);
  75428. })
  75429. .execute();
  75430. areaData.eachItemGraphicEl(function (polygon, idx) {
  75431. var itemModel = areaData.getItemModel(idx);
  75432. var labelModel = itemModel.getModel('label');
  75433. var labelHoverModel = itemModel.getModel('emphasis.label');
  75434. var color = areaData.getItemVisual(idx, 'color');
  75435. polygon.useStyle(
  75436. defaults(
  75437. itemModel.getModel('itemStyle').getItemStyle(),
  75438. {
  75439. fill: modifyAlpha(color, 0.4),
  75440. stroke: color
  75441. }
  75442. )
  75443. );
  75444. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  75445. setLabelStyle(
  75446. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  75447. {
  75448. labelFetcher: maModel,
  75449. labelDataIndex: idx,
  75450. defaultText: areaData.getName(idx) || '',
  75451. isRectText: true,
  75452. autoColor: color
  75453. }
  75454. );
  75455. setHoverStyle(polygon, {});
  75456. polygon.dataModel = maModel;
  75457. });
  75458. polygonGroup.__data = areaData;
  75459. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  75460. }
  75461. });
  75462. /**
  75463. * @inner
  75464. * @param {module:echarts/coord/*} coordSys
  75465. * @param {module:echarts/model/Series} seriesModel
  75466. * @param {module:echarts/model/Model} mpModel
  75467. */
  75468. function createList$3(coordSys, seriesModel, maModel) {
  75469. var coordDimsInfos;
  75470. var areaData;
  75471. var dims = ['x0', 'y0', 'x1', 'y1'];
  75472. if (coordSys) {
  75473. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75474. var data = seriesModel.getData();
  75475. var info = data.getDimensionInfo(
  75476. data.mapDimension(coordDim)
  75477. ) || {};
  75478. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75479. return defaults({name: coordDim}, info);
  75480. });
  75481. areaData = new List(map(dims, function (dim, idx) {
  75482. return {
  75483. name: dim,
  75484. type: coordDimsInfos[idx % 2].type
  75485. };
  75486. }), maModel);
  75487. }
  75488. else {
  75489. coordDimsInfos = [{
  75490. name: 'value',
  75491. type: 'float'
  75492. }];
  75493. areaData = new List(coordDimsInfos, maModel);
  75494. }
  75495. var optData = map(maModel.get('data'), curry(
  75496. markAreaTransform, seriesModel, coordSys, maModel
  75497. ));
  75498. if (coordSys) {
  75499. optData = filter(
  75500. optData, curry(markAreaFilter, coordSys)
  75501. );
  75502. }
  75503. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  75504. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  75505. } : function (item) {
  75506. return item.value;
  75507. };
  75508. areaData.initData(optData, null, dimValueGetter$$1);
  75509. areaData.hasItemOption = true;
  75510. return areaData;
  75511. }
  75512. /*
  75513. * Licensed to the Apache Software Foundation (ASF) under one
  75514. * or more contributor license agreements. See the NOTICE file
  75515. * distributed with this work for additional information
  75516. * regarding copyright ownership. The ASF licenses this file
  75517. * to you under the Apache License, Version 2.0 (the
  75518. * "License"); you may not use this file except in compliance
  75519. * with the License. You may obtain a copy of the License at
  75520. *
  75521. * http://www.apache.org/licenses/LICENSE-2.0
  75522. *
  75523. * Unless required by applicable law or agreed to in writing,
  75524. * software distributed under the License is distributed on an
  75525. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75526. * KIND, either express or implied. See the License for the
  75527. * specific language governing permissions and limitations
  75528. * under the License.
  75529. */
  75530. registerPreprocessor(function (opt) {
  75531. // Make sure markArea component is enabled
  75532. opt.markArea = opt.markArea || {};
  75533. });
  75534. /*
  75535. * Licensed to the Apache Software Foundation (ASF) under one
  75536. * or more contributor license agreements. See the NOTICE file
  75537. * distributed with this work for additional information
  75538. * regarding copyright ownership. The ASF licenses this file
  75539. * to you under the Apache License, Version 2.0 (the
  75540. * "License"); you may not use this file except in compliance
  75541. * with the License. You may obtain a copy of the License at
  75542. *
  75543. * http://www.apache.org/licenses/LICENSE-2.0
  75544. *
  75545. * Unless required by applicable law or agreed to in writing,
  75546. * software distributed under the License is distributed on an
  75547. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75548. * KIND, either express or implied. See the License for the
  75549. * specific language governing permissions and limitations
  75550. * under the License.
  75551. */
  75552. var preprocessor$3 = function (option) {
  75553. var timelineOpt = option && option.timeline;
  75554. if (!isArray(timelineOpt)) {
  75555. timelineOpt = timelineOpt ? [timelineOpt] : [];
  75556. }
  75557. each$1(timelineOpt, function (opt) {
  75558. if (!opt) {
  75559. return;
  75560. }
  75561. compatibleEC2(opt);
  75562. });
  75563. };
  75564. function compatibleEC2(opt) {
  75565. var type = opt.type;
  75566. var ec2Types = {'number': 'value', 'time': 'time'};
  75567. // Compatible with ec2
  75568. if (ec2Types[type]) {
  75569. opt.axisType = ec2Types[type];
  75570. delete opt.type;
  75571. }
  75572. transferItem(opt);
  75573. if (has$2(opt, 'controlPosition')) {
  75574. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  75575. if (!has$2(controlStyle, 'position')) {
  75576. controlStyle.position = opt.controlPosition;
  75577. }
  75578. if (controlStyle.position === 'none' && !has$2(controlStyle, 'show')) {
  75579. controlStyle.show = false;
  75580. delete controlStyle.position;
  75581. }
  75582. delete opt.controlPosition;
  75583. }
  75584. each$1(opt.data || [], function (dataItem) {
  75585. if (isObject$1(dataItem) && !isArray(dataItem)) {
  75586. if (!has$2(dataItem, 'value') && has$2(dataItem, 'name')) {
  75587. // In ec2, using name as value.
  75588. dataItem.value = dataItem.name;
  75589. }
  75590. transferItem(dataItem);
  75591. }
  75592. });
  75593. }
  75594. function transferItem(opt) {
  75595. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  75596. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  75597. // Transfer label out
  75598. var label = opt.label || (opt.label || {});
  75599. var labelNormal = label.normal || (label.normal = {});
  75600. var excludeLabelAttr = {normal: 1, emphasis: 1};
  75601. each$1(label, function (value, name) {
  75602. if (!excludeLabelAttr[name] && !has$2(labelNormal, name)) {
  75603. labelNormal[name] = value;
  75604. }
  75605. });
  75606. if (itemStyleEmphasis.label && !has$2(label, 'emphasis')) {
  75607. label.emphasis = itemStyleEmphasis.label;
  75608. delete itemStyleEmphasis.label;
  75609. }
  75610. }
  75611. function has$2(obj, attr) {
  75612. return obj.hasOwnProperty(attr);
  75613. }
  75614. /*
  75615. * Licensed to the Apache Software Foundation (ASF) under one
  75616. * or more contributor license agreements. See the NOTICE file
  75617. * distributed with this work for additional information
  75618. * regarding copyright ownership. The ASF licenses this file
  75619. * to you under the Apache License, Version 2.0 (the
  75620. * "License"); you may not use this file except in compliance
  75621. * with the License. You may obtain a copy of the License at
  75622. *
  75623. * http://www.apache.org/licenses/LICENSE-2.0
  75624. *
  75625. * Unless required by applicable law or agreed to in writing,
  75626. * software distributed under the License is distributed on an
  75627. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75628. * KIND, either express or implied. See the License for the
  75629. * specific language governing permissions and limitations
  75630. * under the License.
  75631. */
  75632. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  75633. // Only slider now.
  75634. return 'slider';
  75635. });
  75636. /*
  75637. * Licensed to the Apache Software Foundation (ASF) under one
  75638. * or more contributor license agreements. See the NOTICE file
  75639. * distributed with this work for additional information
  75640. * regarding copyright ownership. The ASF licenses this file
  75641. * to you under the Apache License, Version 2.0 (the
  75642. * "License"); you may not use this file except in compliance
  75643. * with the License. You may obtain a copy of the License at
  75644. *
  75645. * http://www.apache.org/licenses/LICENSE-2.0
  75646. *
  75647. * Unless required by applicable law or agreed to in writing,
  75648. * software distributed under the License is distributed on an
  75649. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75650. * KIND, either express or implied. See the License for the
  75651. * specific language governing permissions and limitations
  75652. * under the License.
  75653. */
  75654. registerAction(
  75655. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  75656. function (payload, ecModel) {
  75657. var timelineModel = ecModel.getComponent('timeline');
  75658. if (timelineModel && payload.currentIndex != null) {
  75659. timelineModel.setCurrentIndex(payload.currentIndex);
  75660. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  75661. timelineModel.setPlayState(false);
  75662. }
  75663. }
  75664. // Set normalized currentIndex to payload.
  75665. ecModel.resetOption('timeline');
  75666. return defaults({
  75667. currentIndex: timelineModel.option.currentIndex
  75668. }, payload);
  75669. }
  75670. );
  75671. registerAction(
  75672. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  75673. function (payload, ecModel) {
  75674. var timelineModel = ecModel.getComponent('timeline');
  75675. if (timelineModel && payload.playState != null) {
  75676. timelineModel.setPlayState(payload.playState);
  75677. }
  75678. }
  75679. );
  75680. /*
  75681. * Licensed to the Apache Software Foundation (ASF) under one
  75682. * or more contributor license agreements. See the NOTICE file
  75683. * distributed with this work for additional information
  75684. * regarding copyright ownership. The ASF licenses this file
  75685. * to you under the Apache License, Version 2.0 (the
  75686. * "License"); you may not use this file except in compliance
  75687. * with the License. You may obtain a copy of the License at
  75688. *
  75689. * http://www.apache.org/licenses/LICENSE-2.0
  75690. *
  75691. * Unless required by applicable law or agreed to in writing,
  75692. * software distributed under the License is distributed on an
  75693. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75694. * KIND, either express or implied. See the License for the
  75695. * specific language governing permissions and limitations
  75696. * under the License.
  75697. */
  75698. var TimelineModel = ComponentModel.extend({
  75699. type: 'timeline',
  75700. layoutMode: 'box',
  75701. /**
  75702. * @protected
  75703. */
  75704. defaultOption: {
  75705. zlevel: 0, // 一级层叠
  75706. z: 4, // 二级层叠
  75707. show: true,
  75708. axisType: 'time', // 模式是时间类型,支持 value, category
  75709. realtime: true,
  75710. left: '20%',
  75711. top: null,
  75712. right: '20%',
  75713. bottom: 0,
  75714. width: null,
  75715. height: 40,
  75716. padding: 5,
  75717. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  75718. autoPlay: false,
  75719. rewind: false, // 反向播放
  75720. loop: true,
  75721. playInterval: 2000, // 播放时间间隔,单位ms
  75722. currentIndex: 0,
  75723. itemStyle: {},
  75724. label: {
  75725. color: '#000'
  75726. },
  75727. data: []
  75728. },
  75729. /**
  75730. * @override
  75731. */
  75732. init: function (option, parentModel, ecModel) {
  75733. /**
  75734. * @private
  75735. * @type {module:echarts/data/List}
  75736. */
  75737. this._data;
  75738. /**
  75739. * @private
  75740. * @type {Array.<string>}
  75741. */
  75742. this._names;
  75743. this.mergeDefaultAndTheme(option, ecModel);
  75744. this._initData();
  75745. },
  75746. /**
  75747. * @override
  75748. */
  75749. mergeOption: function (option) {
  75750. TimelineModel.superApply(this, 'mergeOption', arguments);
  75751. this._initData();
  75752. },
  75753. /**
  75754. * @param {number} [currentIndex]
  75755. */
  75756. setCurrentIndex: function (currentIndex) {
  75757. if (currentIndex == null) {
  75758. currentIndex = this.option.currentIndex;
  75759. }
  75760. var count = this._data.count();
  75761. if (this.option.loop) {
  75762. currentIndex = (currentIndex % count + count) % count;
  75763. }
  75764. else {
  75765. currentIndex >= count && (currentIndex = count - 1);
  75766. currentIndex < 0 && (currentIndex = 0);
  75767. }
  75768. this.option.currentIndex = currentIndex;
  75769. },
  75770. /**
  75771. * @return {number} currentIndex
  75772. */
  75773. getCurrentIndex: function () {
  75774. return this.option.currentIndex;
  75775. },
  75776. /**
  75777. * @return {boolean}
  75778. */
  75779. isIndexMax: function () {
  75780. return this.getCurrentIndex() >= this._data.count() - 1;
  75781. },
  75782. /**
  75783. * @param {boolean} state true: play, false: stop
  75784. */
  75785. setPlayState: function (state) {
  75786. this.option.autoPlay = !!state;
  75787. },
  75788. /**
  75789. * @return {boolean} true: play, false: stop
  75790. */
  75791. getPlayState: function () {
  75792. return !!this.option.autoPlay;
  75793. },
  75794. /**
  75795. * @private
  75796. */
  75797. _initData: function () {
  75798. var thisOption = this.option;
  75799. var dataArr = thisOption.data || [];
  75800. var axisType = thisOption.axisType;
  75801. var names = this._names = [];
  75802. if (axisType === 'category') {
  75803. var idxArr = [];
  75804. each$1(dataArr, function (item, index) {
  75805. var value = getDataItemValue(item);
  75806. var newItem;
  75807. if (isObject$1(item)) {
  75808. newItem = clone(item);
  75809. newItem.value = index;
  75810. }
  75811. else {
  75812. newItem = index;
  75813. }
  75814. idxArr.push(newItem);
  75815. if (!isString(value) && (value == null || isNaN(value))) {
  75816. value = '';
  75817. }
  75818. names.push(value + '');
  75819. });
  75820. dataArr = idxArr;
  75821. }
  75822. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  75823. var data = this._data = new List([{name: 'value', type: dimType}], this);
  75824. data.initData(dataArr, names);
  75825. },
  75826. getData: function () {
  75827. return this._data;
  75828. },
  75829. /**
  75830. * @public
  75831. * @return {Array.<string>} categoreis
  75832. */
  75833. getCategories: function () {
  75834. if (this.get('axisType') === 'category') {
  75835. return this._names.slice();
  75836. }
  75837. }
  75838. });
  75839. /*
  75840. * Licensed to the Apache Software Foundation (ASF) under one
  75841. * or more contributor license agreements. See the NOTICE file
  75842. * distributed with this work for additional information
  75843. * regarding copyright ownership. The ASF licenses this file
  75844. * to you under the Apache License, Version 2.0 (the
  75845. * "License"); you may not use this file except in compliance
  75846. * with the License. You may obtain a copy of the License at
  75847. *
  75848. * http://www.apache.org/licenses/LICENSE-2.0
  75849. *
  75850. * Unless required by applicable law or agreed to in writing,
  75851. * software distributed under the License is distributed on an
  75852. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75853. * KIND, either express or implied. See the License for the
  75854. * specific language governing permissions and limitations
  75855. * under the License.
  75856. */
  75857. var SliderTimelineModel = TimelineModel.extend({
  75858. type: 'timeline.slider',
  75859. /**
  75860. * @protected
  75861. */
  75862. defaultOption: {
  75863. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  75864. borderColor: '#ccc', // 时间轴边框颜色
  75865. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  75866. orient: 'horizontal', // 'vertical'
  75867. inverse: false,
  75868. tooltip: { // boolean or Object
  75869. trigger: 'item' // data item may also have tootip attr.
  75870. },
  75871. symbol: 'emptyCircle',
  75872. symbolSize: 10,
  75873. lineStyle: {
  75874. show: true,
  75875. width: 2,
  75876. color: '#304654'
  75877. },
  75878. label: { // 文本标签
  75879. position: 'auto', // auto left right top bottom
  75880. // When using number, label position is not
  75881. // restricted by viewRect.
  75882. // positive: right/bottom, negative: left/top
  75883. show: true,
  75884. interval: 'auto',
  75885. rotate: 0,
  75886. // formatter: null,
  75887. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  75888. color: '#304654'
  75889. },
  75890. itemStyle: {
  75891. color: '#304654',
  75892. borderWidth: 1
  75893. },
  75894. checkpointStyle: {
  75895. symbol: 'circle',
  75896. symbolSize: 13,
  75897. color: '#c23531',
  75898. borderWidth: 5,
  75899. borderColor: 'rgba(194,53,49, 0.5)',
  75900. animation: true,
  75901. animationDuration: 300,
  75902. animationEasing: 'quinticInOut'
  75903. },
  75904. controlStyle: {
  75905. show: true,
  75906. showPlayBtn: true,
  75907. showPrevBtn: true,
  75908. showNextBtn: true,
  75909. itemSize: 22,
  75910. itemGap: 12,
  75911. position: 'left', // 'left' 'right' 'top' 'bottom'
  75912. 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
  75913. 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
  75914. 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
  75915. 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
  75916. color: '#304654',
  75917. borderColor: '#304654',
  75918. borderWidth: 1
  75919. },
  75920. emphasis: {
  75921. label: {
  75922. show: true,
  75923. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  75924. color: '#c23531'
  75925. },
  75926. itemStyle: {
  75927. color: '#c23531'
  75928. },
  75929. controlStyle: {
  75930. color: '#c23531',
  75931. borderColor: '#c23531',
  75932. borderWidth: 2
  75933. }
  75934. },
  75935. data: []
  75936. }
  75937. });
  75938. mixin(SliderTimelineModel, dataFormatMixin);
  75939. /*
  75940. * Licensed to the Apache Software Foundation (ASF) under one
  75941. * or more contributor license agreements. See the NOTICE file
  75942. * distributed with this work for additional information
  75943. * regarding copyright ownership. The ASF licenses this file
  75944. * to you under the Apache License, Version 2.0 (the
  75945. * "License"); you may not use this file except in compliance
  75946. * with the License. You may obtain a copy of the License at
  75947. *
  75948. * http://www.apache.org/licenses/LICENSE-2.0
  75949. *
  75950. * Unless required by applicable law or agreed to in writing,
  75951. * software distributed under the License is distributed on an
  75952. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75953. * KIND, either express or implied. See the License for the
  75954. * specific language governing permissions and limitations
  75955. * under the License.
  75956. */
  75957. var TimelineView = Component.extend({
  75958. type: 'timeline'
  75959. });
  75960. /*
  75961. * Licensed to the Apache Software Foundation (ASF) under one
  75962. * or more contributor license agreements. See the NOTICE file
  75963. * distributed with this work for additional information
  75964. * regarding copyright ownership. The ASF licenses this file
  75965. * to you under the Apache License, Version 2.0 (the
  75966. * "License"); you may not use this file except in compliance
  75967. * with the License. You may obtain a copy of the License at
  75968. *
  75969. * http://www.apache.org/licenses/LICENSE-2.0
  75970. *
  75971. * Unless required by applicable law or agreed to in writing,
  75972. * software distributed under the License is distributed on an
  75973. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75974. * KIND, either express or implied. See the License for the
  75975. * specific language governing permissions and limitations
  75976. * under the License.
  75977. */
  75978. /**
  75979. * Extend axis 2d
  75980. * @constructor module:echarts/coord/cartesian/Axis2D
  75981. * @extends {module:echarts/coord/cartesian/Axis}
  75982. * @param {string} dim
  75983. * @param {*} scale
  75984. * @param {Array.<number>} coordExtent
  75985. * @param {string} axisType
  75986. * @param {string} position
  75987. */
  75988. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  75989. Axis.call(this, dim, scale, coordExtent);
  75990. /**
  75991. * Axis type
  75992. * - 'category'
  75993. * - 'value'
  75994. * - 'time'
  75995. * - 'log'
  75996. * @type {string}
  75997. */
  75998. this.type = axisType || 'value';
  75999. /**
  76000. * Axis model
  76001. * @param {module:echarts/component/TimelineModel}
  76002. */
  76003. this.model = null;
  76004. };
  76005. TimelineAxis.prototype = {
  76006. constructor: TimelineAxis,
  76007. /**
  76008. * @override
  76009. */
  76010. getLabelModel: function () {
  76011. return this.model.getModel('label');
  76012. },
  76013. /**
  76014. * @override
  76015. */
  76016. isHorizontal: function () {
  76017. return this.model.get('orient') === 'horizontal';
  76018. }
  76019. };
  76020. inherits(TimelineAxis, Axis);
  76021. /*
  76022. * Licensed to the Apache Software Foundation (ASF) under one
  76023. * or more contributor license agreements. See the NOTICE file
  76024. * distributed with this work for additional information
  76025. * regarding copyright ownership. The ASF licenses this file
  76026. * to you under the Apache License, Version 2.0 (the
  76027. * "License"); you may not use this file except in compliance
  76028. * with the License. You may obtain a copy of the License at
  76029. *
  76030. * http://www.apache.org/licenses/LICENSE-2.0
  76031. *
  76032. * Unless required by applicable law or agreed to in writing,
  76033. * software distributed under the License is distributed on an
  76034. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76035. * KIND, either express or implied. See the License for the
  76036. * specific language governing permissions and limitations
  76037. * under the License.
  76038. */
  76039. var bind$6 = bind;
  76040. var each$27 = each$1;
  76041. var PI$4 = Math.PI;
  76042. TimelineView.extend({
  76043. type: 'timeline.slider',
  76044. init: function (ecModel, api) {
  76045. this.api = api;
  76046. /**
  76047. * @private
  76048. * @type {module:echarts/component/timeline/TimelineAxis}
  76049. */
  76050. this._axis;
  76051. /**
  76052. * @private
  76053. * @type {module:zrender/core/BoundingRect}
  76054. */
  76055. this._viewRect;
  76056. /**
  76057. * @type {number}
  76058. */
  76059. this._timer;
  76060. /**
  76061. * @type {module:zrender/Element}
  76062. */
  76063. this._currentPointer;
  76064. /**
  76065. * @type {module:zrender/container/Group}
  76066. */
  76067. this._mainGroup;
  76068. /**
  76069. * @type {module:zrender/container/Group}
  76070. */
  76071. this._labelGroup;
  76072. },
  76073. /**
  76074. * @override
  76075. */
  76076. render: function (timelineModel, ecModel, api, payload) {
  76077. this.model = timelineModel;
  76078. this.api = api;
  76079. this.ecModel = ecModel;
  76080. this.group.removeAll();
  76081. if (timelineModel.get('show', true)) {
  76082. var layoutInfo = this._layout(timelineModel, api);
  76083. var mainGroup = this._createGroup('mainGroup');
  76084. var labelGroup = this._createGroup('labelGroup');
  76085. /**
  76086. * @private
  76087. * @type {module:echarts/component/timeline/TimelineAxis}
  76088. */
  76089. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  76090. timelineModel.formatTooltip = function (dataIndex) {
  76091. return encodeHTML(axis.scale.getLabel(dataIndex));
  76092. };
  76093. each$27(
  76094. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  76095. function (name) {
  76096. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  76097. },
  76098. this
  76099. );
  76100. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  76101. this._position(layoutInfo, timelineModel);
  76102. }
  76103. this._doPlayStop();
  76104. },
  76105. /**
  76106. * @override
  76107. */
  76108. remove: function () {
  76109. this._clearTimer();
  76110. this.group.removeAll();
  76111. },
  76112. /**
  76113. * @override
  76114. */
  76115. dispose: function () {
  76116. this._clearTimer();
  76117. },
  76118. _layout: function (timelineModel, api) {
  76119. var labelPosOpt = timelineModel.get('label.position');
  76120. var orient = timelineModel.get('orient');
  76121. var viewRect = getViewRect$4(timelineModel, api);
  76122. // Auto label offset.
  76123. if (labelPosOpt == null || labelPosOpt === 'auto') {
  76124. labelPosOpt = orient === 'horizontal'
  76125. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  76126. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  76127. }
  76128. else if (isNaN(labelPosOpt)) {
  76129. labelPosOpt = ({
  76130. horizontal: {top: '-', bottom: '+'},
  76131. vertical: {left: '-', right: '+'}
  76132. })[orient][labelPosOpt];
  76133. }
  76134. var labelAlignMap = {
  76135. horizontal: 'center',
  76136. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  76137. };
  76138. var labelBaselineMap = {
  76139. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  76140. vertical: 'middle'
  76141. };
  76142. var rotationMap = {
  76143. horizontal: 0,
  76144. vertical: PI$4 / 2
  76145. };
  76146. // Position
  76147. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  76148. var controlModel = timelineModel.getModel('controlStyle');
  76149. var showControl = controlModel.get('show', true);
  76150. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  76151. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  76152. var sizePlusGap = controlSize + controlGap;
  76153. // Special label rotate.
  76154. var labelRotation = timelineModel.get('label.rotate') || 0;
  76155. labelRotation = labelRotation * PI$4 / 180; // To radian.
  76156. var playPosition;
  76157. var prevBtnPosition;
  76158. var nextBtnPosition;
  76159. var axisExtent;
  76160. var controlPosition = controlModel.get('position', true);
  76161. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  76162. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  76163. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  76164. var xLeft = 0;
  76165. var xRight = mainLength;
  76166. // position[0] means left, position[1] means middle.
  76167. if (controlPosition === 'left' || controlPosition === 'bottom') {
  76168. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  76169. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  76170. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  76171. }
  76172. else { // 'top' 'right'
  76173. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  76174. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  76175. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  76176. }
  76177. axisExtent = [xLeft, xRight];
  76178. if (timelineModel.get('inverse')) {
  76179. axisExtent.reverse();
  76180. }
  76181. return {
  76182. viewRect: viewRect,
  76183. mainLength: mainLength,
  76184. orient: orient,
  76185. rotation: rotationMap[orient],
  76186. labelRotation: labelRotation,
  76187. labelPosOpt: labelPosOpt,
  76188. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  76189. labelBaseline: timelineModel.get('label.verticalAlign')
  76190. || timelineModel.get('label.baseline')
  76191. || labelBaselineMap[orient],
  76192. // Based on mainGroup.
  76193. playPosition: playPosition,
  76194. prevBtnPosition: prevBtnPosition,
  76195. nextBtnPosition: nextBtnPosition,
  76196. axisExtent: axisExtent,
  76197. controlSize: controlSize,
  76198. controlGap: controlGap
  76199. };
  76200. },
  76201. _position: function (layoutInfo, timelineModel) {
  76202. // Position is be called finally, because bounding rect is needed for
  76203. // adapt content to fill viewRect (auto adapt offset).
  76204. // Timeline may be not all in the viewRect when 'offset' is specified
  76205. // as a number, because it is more appropriate that label aligns at
  76206. // 'offset' but not the other edge defined by viewRect.
  76207. var mainGroup = this._mainGroup;
  76208. var labelGroup = this._labelGroup;
  76209. var viewRect = layoutInfo.viewRect;
  76210. if (layoutInfo.orient === 'vertical') {
  76211. // transform to horizontal, inverse rotate by left-top point.
  76212. var m = create$1();
  76213. var rotateOriginX = viewRect.x;
  76214. var rotateOriginY = viewRect.y + viewRect.height;
  76215. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  76216. rotate(m, m, -PI$4 / 2);
  76217. translate(m, m, [rotateOriginX, rotateOriginY]);
  76218. viewRect = viewRect.clone();
  76219. viewRect.applyTransform(m);
  76220. }
  76221. var viewBound = getBound(viewRect);
  76222. var mainBound = getBound(mainGroup.getBoundingRect());
  76223. var labelBound = getBound(labelGroup.getBoundingRect());
  76224. var mainPosition = mainGroup.position;
  76225. var labelsPosition = labelGroup.position;
  76226. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  76227. var labelPosOpt = layoutInfo.labelPosOpt;
  76228. if (isNaN(labelPosOpt)) { // '+' or '-'
  76229. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  76230. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  76231. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  76232. }
  76233. else {
  76234. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  76235. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  76236. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  76237. }
  76238. mainGroup.attr('position', mainPosition);
  76239. labelGroup.attr('position', labelsPosition);
  76240. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  76241. setOrigin(mainGroup);
  76242. setOrigin(labelGroup);
  76243. function setOrigin(targetGroup) {
  76244. var pos = targetGroup.position;
  76245. targetGroup.origin = [
  76246. viewBound[0][0] - pos[0],
  76247. viewBound[1][0] - pos[1]
  76248. ];
  76249. }
  76250. function getBound(rect) {
  76251. // [[xmin, xmax], [ymin, ymax]]
  76252. return [
  76253. [rect.x, rect.x + rect.width],
  76254. [rect.y, rect.y + rect.height]
  76255. ];
  76256. }
  76257. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  76258. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  76259. }
  76260. },
  76261. _createAxis: function (layoutInfo, timelineModel) {
  76262. var data = timelineModel.getData();
  76263. var axisType = timelineModel.get('axisType');
  76264. var scale = createScaleByModel(timelineModel, axisType);
  76265. // Customize scale. The `tickValue` is `dataIndex`.
  76266. scale.getTicks = function () {
  76267. return data.mapArray(['value'], function (value) {
  76268. return value;
  76269. });
  76270. };
  76271. var dataExtent = data.getDataExtent('value');
  76272. scale.setExtent(dataExtent[0], dataExtent[1]);
  76273. scale.niceTicks();
  76274. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  76275. axis.model = timelineModel;
  76276. return axis;
  76277. },
  76278. _createGroup: function (name) {
  76279. var newGroup = this['_' + name] = new Group();
  76280. this.group.add(newGroup);
  76281. return newGroup;
  76282. },
  76283. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  76284. var axisExtent = axis.getExtent();
  76285. if (!timelineModel.get('lineStyle.show')) {
  76286. return;
  76287. }
  76288. group.add(new Line({
  76289. shape: {
  76290. x1: axisExtent[0], y1: 0,
  76291. x2: axisExtent[1], y2: 0
  76292. },
  76293. style: extend(
  76294. {lineCap: 'round'},
  76295. timelineModel.getModel('lineStyle').getLineStyle()
  76296. ),
  76297. silent: true,
  76298. z2: 1
  76299. }));
  76300. },
  76301. /**
  76302. * @private
  76303. */
  76304. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  76305. var data = timelineModel.getData();
  76306. // Show all ticks, despite ignoring strategy.
  76307. var ticks = axis.scale.getTicks();
  76308. // The value is dataIndex, see the costomized scale.
  76309. each$27(ticks, function (value) {
  76310. var tickCoord = axis.dataToCoord(value);
  76311. var itemModel = data.getItemModel(value);
  76312. var itemStyleModel = itemModel.getModel('itemStyle');
  76313. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  76314. var symbolOpt = {
  76315. position: [tickCoord, 0],
  76316. onclick: bind$6(this._changeTimeline, this, value)
  76317. };
  76318. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  76319. setHoverStyle(el, hoverStyleModel.getItemStyle());
  76320. if (itemModel.get('tooltip')) {
  76321. el.dataIndex = value;
  76322. el.dataModel = timelineModel;
  76323. }
  76324. else {
  76325. el.dataIndex = el.dataModel = null;
  76326. }
  76327. }, this);
  76328. },
  76329. /**
  76330. * @private
  76331. */
  76332. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  76333. var labelModel = axis.getLabelModel();
  76334. if (!labelModel.get('show')) {
  76335. return;
  76336. }
  76337. var data = timelineModel.getData();
  76338. var labels = axis.getViewLabels();
  76339. each$27(labels, function (labelItem) {
  76340. // The tickValue is dataIndex, see the costomized scale.
  76341. var dataIndex = labelItem.tickValue;
  76342. var itemModel = data.getItemModel(dataIndex);
  76343. var normalLabelModel = itemModel.getModel('label');
  76344. var hoverLabelModel = itemModel.getModel('emphasis.label');
  76345. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  76346. var textEl = new Text({
  76347. position: [tickCoord, 0],
  76348. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  76349. onclick: bind$6(this._changeTimeline, this, dataIndex),
  76350. silent: false
  76351. });
  76352. setTextStyle(textEl.style, normalLabelModel, {
  76353. text: labelItem.formattedLabel,
  76354. textAlign: layoutInfo.labelAlign,
  76355. textVerticalAlign: layoutInfo.labelBaseline
  76356. });
  76357. group.add(textEl);
  76358. setHoverStyle(
  76359. textEl, setTextStyle({}, hoverLabelModel)
  76360. );
  76361. }, this);
  76362. },
  76363. /**
  76364. * @private
  76365. */
  76366. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  76367. var controlSize = layoutInfo.controlSize;
  76368. var rotation = layoutInfo.rotation;
  76369. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  76370. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  76371. var rect = [0, -controlSize / 2, controlSize, controlSize];
  76372. var playState = timelineModel.getPlayState();
  76373. var inverse = timelineModel.get('inverse', true);
  76374. makeBtn(
  76375. layoutInfo.nextBtnPosition,
  76376. 'controlStyle.nextIcon',
  76377. bind$6(this._changeTimeline, this, inverse ? '-' : '+')
  76378. );
  76379. makeBtn(
  76380. layoutInfo.prevBtnPosition,
  76381. 'controlStyle.prevIcon',
  76382. bind$6(this._changeTimeline, this, inverse ? '+' : '-')
  76383. );
  76384. makeBtn(
  76385. layoutInfo.playPosition,
  76386. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  76387. bind$6(this._handlePlayClick, this, !playState),
  76388. true
  76389. );
  76390. function makeBtn(position, iconPath, onclick, willRotate) {
  76391. if (!position) {
  76392. return;
  76393. }
  76394. var opt = {
  76395. position: position,
  76396. origin: [controlSize / 2, 0],
  76397. rotation: willRotate ? -rotation : 0,
  76398. rectHover: true,
  76399. style: itemStyle,
  76400. onclick: onclick
  76401. };
  76402. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  76403. group.add(btn);
  76404. setHoverStyle(btn, hoverStyle);
  76405. }
  76406. },
  76407. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  76408. var data = timelineModel.getData();
  76409. var currentIndex = timelineModel.getCurrentIndex();
  76410. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  76411. var me = this;
  76412. var callback = {
  76413. onCreate: function (pointer) {
  76414. pointer.draggable = true;
  76415. pointer.drift = bind$6(me._handlePointerDrag, me);
  76416. pointer.ondragend = bind$6(me._handlePointerDragend, me);
  76417. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  76418. },
  76419. onUpdate: function (pointer) {
  76420. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  76421. }
  76422. };
  76423. // Reuse when exists, for animation and drag.
  76424. this._currentPointer = giveSymbol(
  76425. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  76426. );
  76427. },
  76428. _handlePlayClick: function (nextState) {
  76429. this._clearTimer();
  76430. this.api.dispatchAction({
  76431. type: 'timelinePlayChange',
  76432. playState: nextState,
  76433. from: this.uid
  76434. });
  76435. },
  76436. _handlePointerDrag: function (dx, dy, e) {
  76437. this._clearTimer();
  76438. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  76439. },
  76440. _handlePointerDragend: function (e) {
  76441. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  76442. },
  76443. _pointerChangeTimeline: function (mousePos, trigger) {
  76444. var toCoord = this._toAxisCoord(mousePos)[0];
  76445. var axis = this._axis;
  76446. var axisExtent = asc(axis.getExtent().slice());
  76447. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  76448. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  76449. this._currentPointer.position[0] = toCoord;
  76450. this._currentPointer.dirty();
  76451. var targetDataIndex = this._findNearestTick(toCoord);
  76452. var timelineModel = this.model;
  76453. if (trigger || (
  76454. targetDataIndex !== timelineModel.getCurrentIndex()
  76455. && timelineModel.get('realtime')
  76456. )) {
  76457. this._changeTimeline(targetDataIndex);
  76458. }
  76459. },
  76460. _doPlayStop: function () {
  76461. this._clearTimer();
  76462. if (this.model.getPlayState()) {
  76463. this._timer = setTimeout(
  76464. bind$6(handleFrame, this),
  76465. this.model.get('playInterval')
  76466. );
  76467. }
  76468. function handleFrame() {
  76469. // Do not cache
  76470. var timelineModel = this.model;
  76471. this._changeTimeline(
  76472. timelineModel.getCurrentIndex()
  76473. + (timelineModel.get('rewind', true) ? -1 : 1)
  76474. );
  76475. }
  76476. },
  76477. _toAxisCoord: function (vertex) {
  76478. var trans = this._mainGroup.getLocalTransform();
  76479. return applyTransform$1(vertex, trans, true);
  76480. },
  76481. _findNearestTick: function (axisCoord) {
  76482. var data = this.model.getData();
  76483. var dist = Infinity;
  76484. var targetDataIndex;
  76485. var axis = this._axis;
  76486. data.each(['value'], function (value, dataIndex) {
  76487. var coord = axis.dataToCoord(value);
  76488. var d = Math.abs(coord - axisCoord);
  76489. if (d < dist) {
  76490. dist = d;
  76491. targetDataIndex = dataIndex;
  76492. }
  76493. });
  76494. return targetDataIndex;
  76495. },
  76496. _clearTimer: function () {
  76497. if (this._timer) {
  76498. clearTimeout(this._timer);
  76499. this._timer = null;
  76500. }
  76501. },
  76502. _changeTimeline: function (nextIndex) {
  76503. var currentIndex = this.model.getCurrentIndex();
  76504. if (nextIndex === '+') {
  76505. nextIndex = currentIndex + 1;
  76506. }
  76507. else if (nextIndex === '-') {
  76508. nextIndex = currentIndex - 1;
  76509. }
  76510. this.api.dispatchAction({
  76511. type: 'timelineChange',
  76512. currentIndex: nextIndex,
  76513. from: this.uid
  76514. });
  76515. }
  76516. });
  76517. function getViewRect$4(model, api) {
  76518. return getLayoutRect(
  76519. model.getBoxLayoutParams(),
  76520. {
  76521. width: api.getWidth(),
  76522. height: api.getHeight()
  76523. },
  76524. model.get('padding')
  76525. );
  76526. }
  76527. function makeIcon(timelineModel, objPath, rect, opts) {
  76528. var icon = makePath(
  76529. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  76530. clone(opts || {}),
  76531. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  76532. 'center'
  76533. );
  76534. return icon;
  76535. }
  76536. /**
  76537. * Create symbol or update symbol
  76538. * opt: basic position and event handlers
  76539. */
  76540. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  76541. var color = itemStyleModel.get('color');
  76542. if (!symbol) {
  76543. var symbolType = hostModel.get('symbol');
  76544. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  76545. symbol.setStyle('strokeNoScale', true);
  76546. group.add(symbol);
  76547. callback && callback.onCreate(symbol);
  76548. }
  76549. else {
  76550. symbol.setColor(color);
  76551. group.add(symbol); // Group may be new, also need to add.
  76552. callback && callback.onUpdate(symbol);
  76553. }
  76554. // Style
  76555. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  76556. symbol.setStyle(itemStyle);
  76557. // Transform and events.
  76558. opt = merge({
  76559. rectHover: true,
  76560. z2: 100
  76561. }, opt, true);
  76562. var symbolSize = hostModel.get('symbolSize');
  76563. symbolSize = symbolSize instanceof Array
  76564. ? symbolSize.slice()
  76565. : [+symbolSize, +symbolSize];
  76566. symbolSize[0] /= 2;
  76567. symbolSize[1] /= 2;
  76568. opt.scale = symbolSize;
  76569. var symbolOffset = hostModel.get('symbolOffset');
  76570. if (symbolOffset) {
  76571. var pos = opt.position = opt.position || [0, 0];
  76572. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  76573. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  76574. }
  76575. var symbolRotate = hostModel.get('symbolRotate');
  76576. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  76577. symbol.attr(opt);
  76578. // FIXME
  76579. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  76580. // getBoundingRect will return wrong result.
  76581. // (This is supposed to be resolved in zrender, but it is a little difficult to
  76582. // leverage performance and auto updateTransform)
  76583. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  76584. symbol.updateTransform();
  76585. return symbol;
  76586. }
  76587. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  76588. if (pointer.dragging) {
  76589. return;
  76590. }
  76591. var pointerModel = timelineModel.getModel('checkpointStyle');
  76592. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  76593. if (noAnimation || !pointerModel.get('animation', true)) {
  76594. pointer.attr({position: [toCoord, 0]});
  76595. }
  76596. else {
  76597. pointer.stopAnimation(true);
  76598. pointer.animateTo(
  76599. {position: [toCoord, 0]},
  76600. pointerModel.get('animationDuration', true),
  76601. pointerModel.get('animationEasing', true)
  76602. );
  76603. }
  76604. }
  76605. /*
  76606. * Licensed to the Apache Software Foundation (ASF) under one
  76607. * or more contributor license agreements. See the NOTICE file
  76608. * distributed with this work for additional information
  76609. * regarding copyright ownership. The ASF licenses this file
  76610. * to you under the Apache License, Version 2.0 (the
  76611. * "License"); you may not use this file except in compliance
  76612. * with the License. You may obtain a copy of the License at
  76613. *
  76614. * http://www.apache.org/licenses/LICENSE-2.0
  76615. *
  76616. * Unless required by applicable law or agreed to in writing,
  76617. * software distributed under the License is distributed on an
  76618. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76619. * KIND, either express or implied. See the License for the
  76620. * specific language governing permissions and limitations
  76621. * under the License.
  76622. */
  76623. /**
  76624. * DataZoom component entry
  76625. */
  76626. registerPreprocessor(preprocessor$3);
  76627. /*
  76628. * Licensed to the Apache Software Foundation (ASF) under one
  76629. * or more contributor license agreements. See the NOTICE file
  76630. * distributed with this work for additional information
  76631. * regarding copyright ownership. The ASF licenses this file
  76632. * to you under the Apache License, Version 2.0 (the
  76633. * "License"); you may not use this file except in compliance
  76634. * with the License. You may obtain a copy of the License at
  76635. *
  76636. * http://www.apache.org/licenses/LICENSE-2.0
  76637. *
  76638. * Unless required by applicable law or agreed to in writing,
  76639. * software distributed under the License is distributed on an
  76640. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76641. * KIND, either express or implied. See the License for the
  76642. * specific language governing permissions and limitations
  76643. * under the License.
  76644. */
  76645. var ToolboxModel = extendComponentModel({
  76646. type: 'toolbox',
  76647. layoutMode: {
  76648. type: 'box',
  76649. ignoreSize: true
  76650. },
  76651. optionUpdated: function () {
  76652. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  76653. each$1(this.option.feature, function (featureOpt, featureName) {
  76654. var Feature = get$1(featureName);
  76655. Feature && merge(featureOpt, Feature.defaultOption);
  76656. });
  76657. },
  76658. defaultOption: {
  76659. show: true,
  76660. z: 6,
  76661. zlevel: 0,
  76662. orient: 'horizontal',
  76663. left: 'right',
  76664. top: 'top',
  76665. // right
  76666. // bottom
  76667. backgroundColor: 'transparent',
  76668. borderColor: '#ccc',
  76669. borderRadius: 0,
  76670. borderWidth: 0,
  76671. padding: 5,
  76672. itemSize: 15,
  76673. itemGap: 8,
  76674. showTitle: true,
  76675. iconStyle: {
  76676. borderColor: '#666',
  76677. color: 'none'
  76678. },
  76679. emphasis: {
  76680. iconStyle: {
  76681. borderColor: '#3E98C5'
  76682. }
  76683. }
  76684. // textStyle: {},
  76685. // feature
  76686. }
  76687. });
  76688. /*
  76689. * Licensed to the Apache Software Foundation (ASF) under one
  76690. * or more contributor license agreements. See the NOTICE file
  76691. * distributed with this work for additional information
  76692. * regarding copyright ownership. The ASF licenses this file
  76693. * to you under the Apache License, Version 2.0 (the
  76694. * "License"); you may not use this file except in compliance
  76695. * with the License. You may obtain a copy of the License at
  76696. *
  76697. * http://www.apache.org/licenses/LICENSE-2.0
  76698. *
  76699. * Unless required by applicable law or agreed to in writing,
  76700. * software distributed under the License is distributed on an
  76701. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76702. * KIND, either express or implied. See the License for the
  76703. * specific language governing permissions and limitations
  76704. * under the License.
  76705. */
  76706. extendComponentView({
  76707. type: 'toolbox',
  76708. render: function (toolboxModel, ecModel, api, payload) {
  76709. var group = this.group;
  76710. group.removeAll();
  76711. if (!toolboxModel.get('show')) {
  76712. return;
  76713. }
  76714. var itemSize = +toolboxModel.get('itemSize');
  76715. var featureOpts = toolboxModel.get('feature') || {};
  76716. var features = this._features || (this._features = {});
  76717. var featureNames = [];
  76718. each$1(featureOpts, function (opt, name) {
  76719. featureNames.push(name);
  76720. });
  76721. (new DataDiffer(this._featureNames || [], featureNames))
  76722. .add(processFeature)
  76723. .update(processFeature)
  76724. .remove(curry(processFeature, null))
  76725. .execute();
  76726. // Keep for diff.
  76727. this._featureNames = featureNames;
  76728. function processFeature(newIndex, oldIndex) {
  76729. var featureName = featureNames[newIndex];
  76730. var oldName = featureNames[oldIndex];
  76731. var featureOpt = featureOpts[featureName];
  76732. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  76733. var feature;
  76734. if (featureName && !oldName) { // Create
  76735. if (isUserFeatureName(featureName)) {
  76736. feature = {
  76737. model: featureModel,
  76738. onclick: featureModel.option.onclick,
  76739. featureName: featureName
  76740. };
  76741. }
  76742. else {
  76743. var Feature = get$1(featureName);
  76744. if (!Feature) {
  76745. return;
  76746. }
  76747. feature = new Feature(featureModel, ecModel, api);
  76748. }
  76749. features[featureName] = feature;
  76750. }
  76751. else {
  76752. feature = features[oldName];
  76753. // If feature does not exsit.
  76754. if (!feature) {
  76755. return;
  76756. }
  76757. feature.model = featureModel;
  76758. feature.ecModel = ecModel;
  76759. feature.api = api;
  76760. }
  76761. if (!featureName && oldName) {
  76762. feature.dispose && feature.dispose(ecModel, api);
  76763. return;
  76764. }
  76765. if (!featureModel.get('show') || feature.unusable) {
  76766. feature.remove && feature.remove(ecModel, api);
  76767. return;
  76768. }
  76769. createIconPaths(featureModel, feature, featureName);
  76770. featureModel.setIconStatus = function (iconName, status) {
  76771. var option = this.option;
  76772. var iconPaths = this.iconPaths;
  76773. option.iconStatus = option.iconStatus || {};
  76774. option.iconStatus[iconName] = status;
  76775. // FIXME
  76776. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  76777. };
  76778. if (feature.render) {
  76779. feature.render(featureModel, ecModel, api, payload);
  76780. }
  76781. }
  76782. function createIconPaths(featureModel, feature, featureName) {
  76783. var iconStyleModel = featureModel.getModel('iconStyle');
  76784. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  76785. // If one feature has mutiple icon. they are orginaized as
  76786. // {
  76787. // icon: {
  76788. // foo: '',
  76789. // bar: ''
  76790. // },
  76791. // title: {
  76792. // foo: '',
  76793. // bar: ''
  76794. // }
  76795. // }
  76796. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  76797. var titles = featureModel.get('title') || {};
  76798. if (typeof icons === 'string') {
  76799. var icon = icons;
  76800. var title = titles;
  76801. icons = {};
  76802. titles = {};
  76803. icons[featureName] = icon;
  76804. titles[featureName] = title;
  76805. }
  76806. var iconPaths = featureModel.iconPaths = {};
  76807. each$1(icons, function (iconStr, iconName) {
  76808. var path = createIcon(
  76809. iconStr,
  76810. {},
  76811. {
  76812. x: -itemSize / 2,
  76813. y: -itemSize / 2,
  76814. width: itemSize,
  76815. height: itemSize
  76816. }
  76817. );
  76818. path.setStyle(iconStyleModel.getItemStyle());
  76819. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  76820. setHoverStyle(path);
  76821. if (toolboxModel.get('showTitle')) {
  76822. path.__title = titles[iconName];
  76823. path.on('mouseover', function () {
  76824. // Should not reuse above hoverStyle, which might be modified.
  76825. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  76826. path.setStyle({
  76827. text: titles[iconName],
  76828. textPosition: hoverStyle.textPosition || 'bottom',
  76829. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  76830. textAlign: hoverStyle.textAlign || 'center'
  76831. });
  76832. })
  76833. .on('mouseout', function () {
  76834. path.setStyle({
  76835. textFill: null
  76836. });
  76837. });
  76838. }
  76839. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  76840. group.add(path);
  76841. path.on('click', bind(
  76842. feature.onclick, feature, ecModel, api, iconName
  76843. ));
  76844. iconPaths[iconName] = path;
  76845. });
  76846. }
  76847. layout$3(group, toolboxModel, api);
  76848. // Render background after group is layout
  76849. // FIXME
  76850. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  76851. // Adjust icon title positions to avoid them out of screen
  76852. group.eachChild(function (icon) {
  76853. var titleText = icon.__title;
  76854. var hoverStyle = icon.hoverStyle;
  76855. // May be background element
  76856. if (hoverStyle && titleText) {
  76857. var rect = getBoundingRect(
  76858. titleText, makeFont(hoverStyle)
  76859. );
  76860. var offsetX = icon.position[0] + group.position[0];
  76861. var offsetY = icon.position[1] + group.position[1] + itemSize;
  76862. var needPutOnTop = false;
  76863. if (offsetY + rect.height > api.getHeight()) {
  76864. hoverStyle.textPosition = 'top';
  76865. needPutOnTop = true;
  76866. }
  76867. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  76868. if (offsetX + rect.width / 2 > api.getWidth()) {
  76869. hoverStyle.textPosition = ['100%', topOffset];
  76870. hoverStyle.textAlign = 'right';
  76871. }
  76872. else if (offsetX - rect.width / 2 < 0) {
  76873. hoverStyle.textPosition = [0, topOffset];
  76874. hoverStyle.textAlign = 'left';
  76875. }
  76876. }
  76877. });
  76878. },
  76879. updateView: function (toolboxModel, ecModel, api, payload) {
  76880. each$1(this._features, function (feature) {
  76881. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  76882. });
  76883. },
  76884. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  76885. // zrUtil.each(this._features, function (feature) {
  76886. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  76887. // });
  76888. // },
  76889. remove: function (ecModel, api) {
  76890. each$1(this._features, function (feature) {
  76891. feature.remove && feature.remove(ecModel, api);
  76892. });
  76893. this.group.removeAll();
  76894. },
  76895. dispose: function (ecModel, api) {
  76896. each$1(this._features, function (feature) {
  76897. feature.dispose && feature.dispose(ecModel, api);
  76898. });
  76899. }
  76900. });
  76901. function isUserFeatureName(featureName) {
  76902. return featureName.indexOf('my') === 0;
  76903. }
  76904. /*
  76905. * Licensed to the Apache Software Foundation (ASF) under one
  76906. * or more contributor license agreements. See the NOTICE file
  76907. * distributed with this work for additional information
  76908. * regarding copyright ownership. The ASF licenses this file
  76909. * to you under the Apache License, Version 2.0 (the
  76910. * "License"); you may not use this file except in compliance
  76911. * with the License. You may obtain a copy of the License at
  76912. *
  76913. * http://www.apache.org/licenses/LICENSE-2.0
  76914. *
  76915. * Unless required by applicable law or agreed to in writing,
  76916. * software distributed under the License is distributed on an
  76917. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76918. * KIND, either express or implied. See the License for the
  76919. * specific language governing permissions and limitations
  76920. * under the License.
  76921. */
  76922. /* global Uint8Array */
  76923. var saveAsImageLang = lang.toolbox.saveAsImage;
  76924. function SaveAsImage(model) {
  76925. this.model = model;
  76926. }
  76927. SaveAsImage.defaultOption = {
  76928. show: true,
  76929. 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',
  76930. title: saveAsImageLang.title,
  76931. type: 'png',
  76932. // Default use option.backgroundColor
  76933. // backgroundColor: '#fff',
  76934. name: '',
  76935. excludeComponents: ['toolbox'],
  76936. pixelRatio: 1,
  76937. lang: saveAsImageLang.lang.slice()
  76938. };
  76939. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  76940. var proto$4 = SaveAsImage.prototype;
  76941. proto$4.onclick = function (ecModel, api) {
  76942. var model = this.model;
  76943. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  76944. var $a = document.createElement('a');
  76945. var type = model.get('type', true) || 'png';
  76946. $a.download = title + '.' + type;
  76947. $a.target = '_blank';
  76948. var url = api.getConnectedDataURL({
  76949. type: type,
  76950. backgroundColor: model.get('backgroundColor', true)
  76951. || ecModel.get('backgroundColor') || '#fff',
  76952. excludeComponents: model.get('excludeComponents'),
  76953. pixelRatio: model.get('pixelRatio')
  76954. });
  76955. $a.href = url;
  76956. // Chrome and Firefox
  76957. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  76958. var evt = new MouseEvent('click', {
  76959. view: window,
  76960. bubbles: true,
  76961. cancelable: false
  76962. });
  76963. $a.dispatchEvent(evt);
  76964. }
  76965. // IE
  76966. else {
  76967. if (window.navigator.msSaveOrOpenBlob) {
  76968. var bstr = atob(url.split(',')[1]);
  76969. var n = bstr.length;
  76970. var u8arr = new Uint8Array(n);
  76971. while (n--) {
  76972. u8arr[n] = bstr.charCodeAt(n);
  76973. }
  76974. var blob = new Blob([u8arr]);
  76975. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  76976. }
  76977. else {
  76978. var lang$$1 = model.get('lang');
  76979. var html = ''
  76980. + '<body style="margin:0;">'
  76981. + '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />'
  76982. + '</body>';
  76983. var tab = window.open();
  76984. tab.document.write(html);
  76985. }
  76986. }
  76987. };
  76988. register$1(
  76989. 'saveAsImage', SaveAsImage
  76990. );
  76991. /*
  76992. * Licensed to the Apache Software Foundation (ASF) under one
  76993. * or more contributor license agreements. See the NOTICE file
  76994. * distributed with this work for additional information
  76995. * regarding copyright ownership. The ASF licenses this file
  76996. * to you under the Apache License, Version 2.0 (the
  76997. * "License"); you may not use this file except in compliance
  76998. * with the License. You may obtain a copy of the License at
  76999. *
  77000. * http://www.apache.org/licenses/LICENSE-2.0
  77001. *
  77002. * Unless required by applicable law or agreed to in writing,
  77003. * software distributed under the License is distributed on an
  77004. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77005. * KIND, either express or implied. See the License for the
  77006. * specific language governing permissions and limitations
  77007. * under the License.
  77008. */
  77009. var magicTypeLang = lang.toolbox.magicType;
  77010. function MagicType(model) {
  77011. this.model = model;
  77012. }
  77013. MagicType.defaultOption = {
  77014. show: true,
  77015. type: [],
  77016. // Icon group
  77017. icon: {
  77018. /* eslint-disable */
  77019. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  77020. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  77021. 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
  77022. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  77023. /* eslint-enable */
  77024. },
  77025. // `line`, `bar`, `stack`, `tiled`
  77026. title: clone(magicTypeLang.title),
  77027. option: {},
  77028. seriesIndex: {}
  77029. };
  77030. var proto$5 = MagicType.prototype;
  77031. proto$5.getIcons = function () {
  77032. var model = this.model;
  77033. var availableIcons = model.get('icon');
  77034. var icons = {};
  77035. each$1(model.get('type'), function (type) {
  77036. if (availableIcons[type]) {
  77037. icons[type] = availableIcons[type];
  77038. }
  77039. });
  77040. return icons;
  77041. };
  77042. var seriesOptGenreator = {
  77043. 'line': function (seriesType, seriesId, seriesModel, model) {
  77044. if (seriesType === 'bar') {
  77045. return merge({
  77046. id: seriesId,
  77047. type: 'line',
  77048. // Preserve data related option
  77049. data: seriesModel.get('data'),
  77050. stack: seriesModel.get('stack'),
  77051. markPoint: seriesModel.get('markPoint'),
  77052. markLine: seriesModel.get('markLine')
  77053. }, model.get('option.line') || {}, true);
  77054. }
  77055. },
  77056. 'bar': function (seriesType, seriesId, seriesModel, model) {
  77057. if (seriesType === 'line') {
  77058. return merge({
  77059. id: seriesId,
  77060. type: 'bar',
  77061. // Preserve data related option
  77062. data: seriesModel.get('data'),
  77063. stack: seriesModel.get('stack'),
  77064. markPoint: seriesModel.get('markPoint'),
  77065. markLine: seriesModel.get('markLine')
  77066. }, model.get('option.bar') || {}, true);
  77067. }
  77068. },
  77069. 'stack': function (seriesType, seriesId, seriesModel, model) {
  77070. if (seriesType === 'line' || seriesType === 'bar') {
  77071. return merge({
  77072. id: seriesId,
  77073. stack: '__ec_magicType_stack__'
  77074. }, model.get('option.stack') || {}, true);
  77075. }
  77076. },
  77077. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  77078. if (seriesType === 'line' || seriesType === 'bar') {
  77079. return merge({
  77080. id: seriesId,
  77081. stack: ''
  77082. }, model.get('option.tiled') || {}, true);
  77083. }
  77084. }
  77085. };
  77086. var radioTypes = [
  77087. ['line', 'bar'],
  77088. ['stack', 'tiled']
  77089. ];
  77090. proto$5.onclick = function (ecModel, api, type) {
  77091. var model = this.model;
  77092. var seriesIndex = model.get('seriesIndex.' + type);
  77093. // Not supported magicType
  77094. if (!seriesOptGenreator[type]) {
  77095. return;
  77096. }
  77097. var newOption = {
  77098. series: []
  77099. };
  77100. var generateNewSeriesTypes = function (seriesModel) {
  77101. var seriesType = seriesModel.subType;
  77102. var seriesId = seriesModel.id;
  77103. var newSeriesOpt = seriesOptGenreator[type](
  77104. seriesType, seriesId, seriesModel, model
  77105. );
  77106. if (newSeriesOpt) {
  77107. // PENDING If merge original option?
  77108. defaults(newSeriesOpt, seriesModel.option);
  77109. newOption.series.push(newSeriesOpt);
  77110. }
  77111. // Modify boundaryGap
  77112. var coordSys = seriesModel.coordinateSystem;
  77113. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  77114. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  77115. if (categoryAxis) {
  77116. var axisDim = categoryAxis.dim;
  77117. var axisType = axisDim + 'Axis';
  77118. var axisModel = ecModel.queryComponents({
  77119. mainType: axisType,
  77120. index: seriesModel.get(name + 'Index'),
  77121. id: seriesModel.get(name + 'Id')
  77122. })[0];
  77123. var axisIndex = axisModel.componentIndex;
  77124. newOption[axisType] = newOption[axisType] || [];
  77125. for (var i = 0; i <= axisIndex; i++) {
  77126. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  77127. }
  77128. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  77129. }
  77130. }
  77131. };
  77132. each$1(radioTypes, function (radio) {
  77133. if (indexOf(radio, type) >= 0) {
  77134. each$1(radio, function (item) {
  77135. model.setIconStatus(item, 'normal');
  77136. });
  77137. }
  77138. });
  77139. model.setIconStatus(type, 'emphasis');
  77140. ecModel.eachComponent(
  77141. {
  77142. mainType: 'series',
  77143. query: seriesIndex == null ? null : {
  77144. seriesIndex: seriesIndex
  77145. }
  77146. }, generateNewSeriesTypes
  77147. );
  77148. api.dispatchAction({
  77149. type: 'changeMagicType',
  77150. currentType: type,
  77151. newOption: newOption
  77152. });
  77153. };
  77154. registerAction({
  77155. type: 'changeMagicType',
  77156. event: 'magicTypeChanged',
  77157. update: 'prepareAndUpdate'
  77158. }, function (payload, ecModel) {
  77159. ecModel.mergeOption(payload.newOption);
  77160. });
  77161. register$1('magicType', MagicType);
  77162. /*
  77163. * Licensed to the Apache Software Foundation (ASF) under one
  77164. * or more contributor license agreements. See the NOTICE file
  77165. * distributed with this work for additional information
  77166. * regarding copyright ownership. The ASF licenses this file
  77167. * to you under the Apache License, Version 2.0 (the
  77168. * "License"); you may not use this file except in compliance
  77169. * with the License. You may obtain a copy of the License at
  77170. *
  77171. * http://www.apache.org/licenses/LICENSE-2.0
  77172. *
  77173. * Unless required by applicable law or agreed to in writing,
  77174. * software distributed under the License is distributed on an
  77175. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77176. * KIND, either express or implied. See the License for the
  77177. * specific language governing permissions and limitations
  77178. * under the License.
  77179. */
  77180. var dataViewLang = lang.toolbox.dataView;
  77181. var BLOCK_SPLITER = new Array(60).join('-');
  77182. var ITEM_SPLITER = '\t';
  77183. /**
  77184. * Group series into two types
  77185. * 1. on category axis, like line, bar
  77186. * 2. others, like scatter, pie
  77187. * @param {module:echarts/model/Global} ecModel
  77188. * @return {Object}
  77189. * @inner
  77190. */
  77191. function groupSeries(ecModel) {
  77192. var seriesGroupByCategoryAxis = {};
  77193. var otherSeries = [];
  77194. var meta = [];
  77195. ecModel.eachRawSeries(function (seriesModel) {
  77196. var coordSys = seriesModel.coordinateSystem;
  77197. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  77198. var baseAxis = coordSys.getBaseAxis();
  77199. if (baseAxis.type === 'category') {
  77200. var key = baseAxis.dim + '_' + baseAxis.index;
  77201. if (!seriesGroupByCategoryAxis[key]) {
  77202. seriesGroupByCategoryAxis[key] = {
  77203. categoryAxis: baseAxis,
  77204. valueAxis: coordSys.getOtherAxis(baseAxis),
  77205. series: []
  77206. };
  77207. meta.push({
  77208. axisDim: baseAxis.dim,
  77209. axisIndex: baseAxis.index
  77210. });
  77211. }
  77212. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  77213. }
  77214. else {
  77215. otherSeries.push(seriesModel);
  77216. }
  77217. }
  77218. else {
  77219. otherSeries.push(seriesModel);
  77220. }
  77221. });
  77222. return {
  77223. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  77224. other: otherSeries,
  77225. meta: meta
  77226. };
  77227. }
  77228. /**
  77229. * Assemble content of series on cateogory axis
  77230. * @param {Array.<module:echarts/model/Series>} series
  77231. * @return {string}
  77232. * @inner
  77233. */
  77234. function assembleSeriesWithCategoryAxis(series) {
  77235. var tables = [];
  77236. each$1(series, function (group, key) {
  77237. var categoryAxis = group.categoryAxis;
  77238. var valueAxis = group.valueAxis;
  77239. var valueAxisDim = valueAxis.dim;
  77240. var headers = [' '].concat(map(group.series, function (series) {
  77241. return series.name;
  77242. }));
  77243. var columns = [categoryAxis.model.getCategories()];
  77244. each$1(group.series, function (series) {
  77245. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  77246. return val;
  77247. }));
  77248. });
  77249. // Assemble table content
  77250. var lines = [headers.join(ITEM_SPLITER)];
  77251. for (var i = 0; i < columns[0].length; i++) {
  77252. var items = [];
  77253. for (var j = 0; j < columns.length; j++) {
  77254. items.push(columns[j][i]);
  77255. }
  77256. lines.push(items.join(ITEM_SPLITER));
  77257. }
  77258. tables.push(lines.join('\n'));
  77259. });
  77260. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  77261. }
  77262. /**
  77263. * Assemble content of other series
  77264. * @param {Array.<module:echarts/model/Series>} series
  77265. * @return {string}
  77266. * @inner
  77267. */
  77268. function assembleOtherSeries(series) {
  77269. return map(series, function (series) {
  77270. var data = series.getRawData();
  77271. var lines = [series.name];
  77272. var vals = [];
  77273. data.each(data.dimensions, function () {
  77274. var argLen = arguments.length;
  77275. var dataIndex = arguments[argLen - 1];
  77276. var name = data.getName(dataIndex);
  77277. for (var i = 0; i < argLen - 1; i++) {
  77278. vals[i] = arguments[i];
  77279. }
  77280. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  77281. });
  77282. return lines.join('\n');
  77283. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  77284. }
  77285. /**
  77286. * @param {module:echarts/model/Global}
  77287. * @return {Object}
  77288. * @inner
  77289. */
  77290. function getContentFromModel(ecModel) {
  77291. var result = groupSeries(ecModel);
  77292. return {
  77293. value: filter([
  77294. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  77295. assembleOtherSeries(result.other)
  77296. ], function (str) {
  77297. return str.replace(/[\n\t\s]/g, '');
  77298. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  77299. meta: result.meta
  77300. };
  77301. }
  77302. function trim$1(str) {
  77303. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  77304. }
  77305. /**
  77306. * If a block is tsv format
  77307. */
  77308. function isTSVFormat(block) {
  77309. // Simple method to find out if a block is tsv format
  77310. var firstLine = block.slice(0, block.indexOf('\n'));
  77311. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  77312. return true;
  77313. }
  77314. }
  77315. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  77316. /**
  77317. * @param {string} tsv
  77318. * @return {Object}
  77319. */
  77320. function parseTSVContents(tsv) {
  77321. var tsvLines = tsv.split(/\n+/g);
  77322. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  77323. var categories = [];
  77324. var series = map(headers, function (header) {
  77325. return {
  77326. name: header,
  77327. data: []
  77328. };
  77329. });
  77330. for (var i = 0; i < tsvLines.length; i++) {
  77331. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  77332. categories.push(items.shift());
  77333. for (var j = 0; j < items.length; j++) {
  77334. series[j] && (series[j].data[i] = items[j]);
  77335. }
  77336. }
  77337. return {
  77338. series: series,
  77339. categories: categories
  77340. };
  77341. }
  77342. /**
  77343. * @param {string} str
  77344. * @return {Array.<Object>}
  77345. * @inner
  77346. */
  77347. function parseListContents(str) {
  77348. var lines = str.split(/\n+/g);
  77349. var seriesName = trim$1(lines.shift());
  77350. var data = [];
  77351. for (var i = 0; i < lines.length; i++) {
  77352. var items = trim$1(lines[i]).split(itemSplitRegex);
  77353. var name = '';
  77354. var value;
  77355. var hasName = false;
  77356. if (isNaN(items[0])) { // First item is name
  77357. hasName = true;
  77358. name = items[0];
  77359. items = items.slice(1);
  77360. data[i] = {
  77361. name: name,
  77362. value: []
  77363. };
  77364. value = data[i].value;
  77365. }
  77366. else {
  77367. value = data[i] = [];
  77368. }
  77369. for (var j = 0; j < items.length; j++) {
  77370. value.push(+items[j]);
  77371. }
  77372. if (value.length === 1) {
  77373. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  77374. }
  77375. }
  77376. return {
  77377. name: seriesName,
  77378. data: data
  77379. };
  77380. }
  77381. /**
  77382. * @param {string} str
  77383. * @param {Array.<Object>} blockMetaList
  77384. * @return {Object}
  77385. * @inner
  77386. */
  77387. function parseContents(str, blockMetaList) {
  77388. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  77389. var newOption = {
  77390. series: []
  77391. };
  77392. each$1(blocks, function (block, idx) {
  77393. if (isTSVFormat(block)) {
  77394. var result = parseTSVContents(block);
  77395. var blockMeta = blockMetaList[idx];
  77396. var axisKey = blockMeta.axisDim + 'Axis';
  77397. if (blockMeta) {
  77398. newOption[axisKey] = newOption[axisKey] || [];
  77399. newOption[axisKey][blockMeta.axisIndex] = {
  77400. data: result.categories
  77401. };
  77402. newOption.series = newOption.series.concat(result.series);
  77403. }
  77404. }
  77405. else {
  77406. var result = parseListContents(block);
  77407. newOption.series.push(result);
  77408. }
  77409. });
  77410. return newOption;
  77411. }
  77412. /**
  77413. * @alias {module:echarts/component/toolbox/feature/DataView}
  77414. * @constructor
  77415. * @param {module:echarts/model/Model} model
  77416. */
  77417. function DataView(model) {
  77418. this._dom = null;
  77419. this.model = model;
  77420. }
  77421. DataView.defaultOption = {
  77422. show: true,
  77423. readOnly: false,
  77424. optionToContent: null,
  77425. contentToOption: null,
  77426. 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',
  77427. title: clone(dataViewLang.title),
  77428. lang: clone(dataViewLang.lang),
  77429. backgroundColor: '#fff',
  77430. textColor: '#000',
  77431. textareaColor: '#fff',
  77432. textareaBorderColor: '#333',
  77433. buttonColor: '#c23531',
  77434. buttonTextColor: '#fff'
  77435. };
  77436. DataView.prototype.onclick = function (ecModel, api) {
  77437. var container = api.getDom();
  77438. var model = this.model;
  77439. if (this._dom) {
  77440. container.removeChild(this._dom);
  77441. }
  77442. var root = document.createElement('div');
  77443. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  77444. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  77445. // Create elements
  77446. var header = document.createElement('h4');
  77447. var lang$$1 = model.get('lang') || [];
  77448. header.innerHTML = lang$$1[0] || model.get('title');
  77449. header.style.cssText = 'margin: 10px 20px;';
  77450. header.style.color = model.get('textColor');
  77451. var viewMain = document.createElement('div');
  77452. var textarea = document.createElement('textarea');
  77453. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  77454. var optionToContent = model.get('optionToContent');
  77455. var contentToOption = model.get('contentToOption');
  77456. var result = getContentFromModel(ecModel);
  77457. if (typeof optionToContent === 'function') {
  77458. var htmlOrDom = optionToContent(api.getOption());
  77459. if (typeof htmlOrDom === 'string') {
  77460. viewMain.innerHTML = htmlOrDom;
  77461. }
  77462. else if (isDom(htmlOrDom)) {
  77463. viewMain.appendChild(htmlOrDom);
  77464. }
  77465. }
  77466. else {
  77467. // Use default textarea
  77468. viewMain.appendChild(textarea);
  77469. textarea.readOnly = model.get('readOnly');
  77470. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  77471. textarea.style.color = model.get('textColor');
  77472. textarea.style.borderColor = model.get('textareaBorderColor');
  77473. textarea.style.backgroundColor = model.get('textareaColor');
  77474. textarea.value = result.value;
  77475. }
  77476. var blockMetaList = result.meta;
  77477. var buttonContainer = document.createElement('div');
  77478. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  77479. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  77480. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  77481. var closeButton = document.createElement('div');
  77482. var refreshButton = document.createElement('div');
  77483. buttonStyle += ';background-color:' + model.get('buttonColor');
  77484. buttonStyle += ';color:' + model.get('buttonTextColor');
  77485. var self = this;
  77486. function close() {
  77487. container.removeChild(root);
  77488. self._dom = null;
  77489. }
  77490. addEventListener(closeButton, 'click', close);
  77491. addEventListener(refreshButton, 'click', function () {
  77492. var newOption;
  77493. try {
  77494. if (typeof contentToOption === 'function') {
  77495. newOption = contentToOption(viewMain, api.getOption());
  77496. }
  77497. else {
  77498. newOption = parseContents(textarea.value, blockMetaList);
  77499. }
  77500. }
  77501. catch (e) {
  77502. close();
  77503. throw new Error('Data view format error ' + e);
  77504. }
  77505. if (newOption) {
  77506. api.dispatchAction({
  77507. type: 'changeDataView',
  77508. newOption: newOption
  77509. });
  77510. }
  77511. close();
  77512. });
  77513. closeButton.innerHTML = lang$$1[1];
  77514. refreshButton.innerHTML = lang$$1[2];
  77515. refreshButton.style.cssText = buttonStyle;
  77516. closeButton.style.cssText = buttonStyle;
  77517. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  77518. buttonContainer.appendChild(closeButton);
  77519. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  77520. addEventListener(textarea, 'keydown', function (e) {
  77521. if ((e.keyCode || e.which) === 9) {
  77522. // get caret position/selection
  77523. var val = this.value;
  77524. var start = this.selectionStart;
  77525. var end = this.selectionEnd;
  77526. // set textarea value to: text before caret + tab + text after caret
  77527. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  77528. // put caret at right position again
  77529. this.selectionStart = this.selectionEnd = start + 1;
  77530. // prevent the focus lose
  77531. stop(e);
  77532. }
  77533. });
  77534. root.appendChild(header);
  77535. root.appendChild(viewMain);
  77536. root.appendChild(buttonContainer);
  77537. viewMain.style.height = (container.clientHeight - 80) + 'px';
  77538. container.appendChild(root);
  77539. this._dom = root;
  77540. };
  77541. DataView.prototype.remove = function (ecModel, api) {
  77542. this._dom && api.getDom().removeChild(this._dom);
  77543. };
  77544. DataView.prototype.dispose = function (ecModel, api) {
  77545. this.remove(ecModel, api);
  77546. };
  77547. /**
  77548. * @inner
  77549. */
  77550. function tryMergeDataOption(newData, originalData) {
  77551. return map(newData, function (newVal, idx) {
  77552. var original = originalData && originalData[idx];
  77553. if (isObject$1(original) && !isArray(original)) {
  77554. if (isObject$1(newVal) && !isArray(newVal)) {
  77555. newVal = newVal.value;
  77556. }
  77557. // Original data has option
  77558. return defaults({
  77559. value: newVal
  77560. }, original);
  77561. }
  77562. else {
  77563. return newVal;
  77564. }
  77565. });
  77566. }
  77567. register$1('dataView', DataView);
  77568. registerAction({
  77569. type: 'changeDataView',
  77570. event: 'dataViewChanged',
  77571. update: 'prepareAndUpdate'
  77572. }, function (payload, ecModel) {
  77573. var newSeriesOptList = [];
  77574. each$1(payload.newOption.series, function (seriesOpt) {
  77575. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  77576. if (!seriesModel) {
  77577. // New created series
  77578. // Geuss the series type
  77579. newSeriesOptList.push(extend({
  77580. // Default is scatter
  77581. type: 'scatter'
  77582. }, seriesOpt));
  77583. }
  77584. else {
  77585. var originalData = seriesModel.get('data');
  77586. newSeriesOptList.push({
  77587. name: seriesOpt.name,
  77588. data: tryMergeDataOption(seriesOpt.data, originalData)
  77589. });
  77590. }
  77591. });
  77592. ecModel.mergeOption(defaults({
  77593. series: newSeriesOptList
  77594. }, payload.newOption));
  77595. });
  77596. /*
  77597. * Licensed to the Apache Software Foundation (ASF) under one
  77598. * or more contributor license agreements. See the NOTICE file
  77599. * distributed with this work for additional information
  77600. * regarding copyright ownership. The ASF licenses this file
  77601. * to you under the Apache License, Version 2.0 (the
  77602. * "License"); you may not use this file except in compliance
  77603. * with the License. You may obtain a copy of the License at
  77604. *
  77605. * http://www.apache.org/licenses/LICENSE-2.0
  77606. *
  77607. * Unless required by applicable law or agreed to in writing,
  77608. * software distributed under the License is distributed on an
  77609. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77610. * KIND, either express or implied. See the License for the
  77611. * specific language governing permissions and limitations
  77612. * under the License.
  77613. */
  77614. var each$29 = each$1;
  77615. var ATTR$2 = '\0_ec_hist_store';
  77616. /**
  77617. * @param {module:echarts/model/Global} ecModel
  77618. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  77619. */
  77620. function push(ecModel, newSnapshot) {
  77621. var store = giveStore$1(ecModel);
  77622. // If previous dataZoom can not be found,
  77623. // complete an range with current range.
  77624. each$29(newSnapshot, function (batchItem, dataZoomId) {
  77625. var i = store.length - 1;
  77626. for (; i >= 0; i--) {
  77627. var snapshot = store[i];
  77628. if (snapshot[dataZoomId]) {
  77629. break;
  77630. }
  77631. }
  77632. if (i < 0) {
  77633. // No origin range set, create one by current range.
  77634. var dataZoomModel = ecModel.queryComponents(
  77635. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  77636. )[0];
  77637. if (dataZoomModel) {
  77638. var percentRange = dataZoomModel.getPercentRange();
  77639. store[0][dataZoomId] = {
  77640. dataZoomId: dataZoomId,
  77641. start: percentRange[0],
  77642. end: percentRange[1]
  77643. };
  77644. }
  77645. }
  77646. });
  77647. store.push(newSnapshot);
  77648. }
  77649. /**
  77650. * @param {module:echarts/model/Global} ecModel
  77651. * @return {Object} snapshot
  77652. */
  77653. function pop(ecModel) {
  77654. var store = giveStore$1(ecModel);
  77655. var head = store[store.length - 1];
  77656. store.length > 1 && store.pop();
  77657. // Find top for all dataZoom.
  77658. var snapshot = {};
  77659. each$29(head, function (batchItem, dataZoomId) {
  77660. for (var i = store.length - 1; i >= 0; i--) {
  77661. var batchItem = store[i][dataZoomId];
  77662. if (batchItem) {
  77663. snapshot[dataZoomId] = batchItem;
  77664. break;
  77665. }
  77666. }
  77667. });
  77668. return snapshot;
  77669. }
  77670. /**
  77671. * @param {module:echarts/model/Global} ecModel
  77672. */
  77673. function clear$1(ecModel) {
  77674. ecModel[ATTR$2] = null;
  77675. }
  77676. /**
  77677. * @param {module:echarts/model/Global} ecModel
  77678. * @return {number} records. always >= 1.
  77679. */
  77680. function count(ecModel) {
  77681. return giveStore$1(ecModel).length;
  77682. }
  77683. /**
  77684. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  77685. * History length of each dataZoom may be different.
  77686. * this._history[0] is used to store origin range.
  77687. * @type {Array.<Object>}
  77688. */
  77689. function giveStore$1(ecModel) {
  77690. var store = ecModel[ATTR$2];
  77691. if (!store) {
  77692. store = ecModel[ATTR$2] = [{}];
  77693. }
  77694. return store;
  77695. }
  77696. /*
  77697. * Licensed to the Apache Software Foundation (ASF) under one
  77698. * or more contributor license agreements. See the NOTICE file
  77699. * distributed with this work for additional information
  77700. * regarding copyright ownership. The ASF licenses this file
  77701. * to you under the Apache License, Version 2.0 (the
  77702. * "License"); you may not use this file except in compliance
  77703. * with the License. You may obtain a copy of the License at
  77704. *
  77705. * http://www.apache.org/licenses/LICENSE-2.0
  77706. *
  77707. * Unless required by applicable law or agreed to in writing,
  77708. * software distributed under the License is distributed on an
  77709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77710. * KIND, either express or implied. See the License for the
  77711. * specific language governing permissions and limitations
  77712. * under the License.
  77713. */
  77714. DataZoomModel.extend({
  77715. type: 'dataZoom.select'
  77716. });
  77717. /*
  77718. * Licensed to the Apache Software Foundation (ASF) under one
  77719. * or more contributor license agreements. See the NOTICE file
  77720. * distributed with this work for additional information
  77721. * regarding copyright ownership. The ASF licenses this file
  77722. * to you under the Apache License, Version 2.0 (the
  77723. * "License"); you may not use this file except in compliance
  77724. * with the License. You may obtain a copy of the License at
  77725. *
  77726. * http://www.apache.org/licenses/LICENSE-2.0
  77727. *
  77728. * Unless required by applicable law or agreed to in writing,
  77729. * software distributed under the License is distributed on an
  77730. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77731. * KIND, either express or implied. See the License for the
  77732. * specific language governing permissions and limitations
  77733. * under the License.
  77734. */
  77735. DataZoomView.extend({
  77736. type: 'dataZoom.select'
  77737. });
  77738. /*
  77739. * Licensed to the Apache Software Foundation (ASF) under one
  77740. * or more contributor license agreements. See the NOTICE file
  77741. * distributed with this work for additional information
  77742. * regarding copyright ownership. The ASF licenses this file
  77743. * to you under the Apache License, Version 2.0 (the
  77744. * "License"); you may not use this file except in compliance
  77745. * with the License. You may obtain a copy of the License at
  77746. *
  77747. * http://www.apache.org/licenses/LICENSE-2.0
  77748. *
  77749. * Unless required by applicable law or agreed to in writing,
  77750. * software distributed under the License is distributed on an
  77751. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77752. * KIND, either express or implied. See the License for the
  77753. * specific language governing permissions and limitations
  77754. * under the License.
  77755. */
  77756. /**
  77757. * DataZoom component entry
  77758. */
  77759. /*
  77760. * Licensed to the Apache Software Foundation (ASF) under one
  77761. * or more contributor license agreements. See the NOTICE file
  77762. * distributed with this work for additional information
  77763. * regarding copyright ownership. The ASF licenses this file
  77764. * to you under the Apache License, Version 2.0 (the
  77765. * "License"); you may not use this file except in compliance
  77766. * with the License. You may obtain a copy of the License at
  77767. *
  77768. * http://www.apache.org/licenses/LICENSE-2.0
  77769. *
  77770. * Unless required by applicable law or agreed to in writing,
  77771. * software distributed under the License is distributed on an
  77772. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77773. * KIND, either express or implied. See the License for the
  77774. * specific language governing permissions and limitations
  77775. * under the License.
  77776. */
  77777. // Use dataZoomSelect
  77778. var dataZoomLang = lang.toolbox.dataZoom;
  77779. var each$28 = each$1;
  77780. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  77781. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  77782. function DataZoom(model, ecModel, api) {
  77783. /**
  77784. * @private
  77785. * @type {module:echarts/component/helper/BrushController}
  77786. */
  77787. (this._brushController = new BrushController(api.getZr()))
  77788. .on('brush', bind(this._onBrush, this))
  77789. .mount();
  77790. /**
  77791. * @private
  77792. * @type {boolean}
  77793. */
  77794. this._isZoomActive;
  77795. }
  77796. DataZoom.defaultOption = {
  77797. show: true,
  77798. // Icon group
  77799. icon: {
  77800. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  77801. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  77802. },
  77803. // `zoom`, `back`
  77804. title: clone(dataZoomLang.title)
  77805. };
  77806. var proto$6 = DataZoom.prototype;
  77807. proto$6.render = function (featureModel, ecModel, api, payload) {
  77808. this.model = featureModel;
  77809. this.ecModel = ecModel;
  77810. this.api = api;
  77811. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  77812. updateBackBtnStatus(featureModel, ecModel);
  77813. };
  77814. proto$6.onclick = function (ecModel, api, type) {
  77815. handlers$1[type].call(this);
  77816. };
  77817. proto$6.remove = function (ecModel, api) {
  77818. this._brushController.unmount();
  77819. };
  77820. proto$6.dispose = function (ecModel, api) {
  77821. this._brushController.dispose();
  77822. };
  77823. /**
  77824. * @private
  77825. */
  77826. var handlers$1 = {
  77827. zoom: function () {
  77828. var nextActive = !this._isZoomActive;
  77829. this.api.dispatchAction({
  77830. type: 'takeGlobalCursor',
  77831. key: 'dataZoomSelect',
  77832. dataZoomSelectActive: nextActive
  77833. });
  77834. },
  77835. back: function () {
  77836. this._dispatchZoomAction(pop(this.ecModel));
  77837. }
  77838. };
  77839. /**
  77840. * @private
  77841. */
  77842. proto$6._onBrush = function (areas, opt) {
  77843. if (!opt.isEnd || !areas.length) {
  77844. return;
  77845. }
  77846. var snapshot = {};
  77847. var ecModel = this.ecModel;
  77848. this._brushController.updateCovers([]); // remove cover
  77849. var brushTargetManager = new BrushTargetManager(
  77850. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  77851. );
  77852. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  77853. if (coordSys.type !== 'cartesian2d') {
  77854. return;
  77855. }
  77856. var brushType = area.brushType;
  77857. if (brushType === 'rect') {
  77858. setBatch('x', coordSys, coordRange[0]);
  77859. setBatch('y', coordSys, coordRange[1]);
  77860. }
  77861. else {
  77862. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  77863. }
  77864. });
  77865. push(ecModel, snapshot);
  77866. this._dispatchZoomAction(snapshot);
  77867. function setBatch(dimName, coordSys, minMax) {
  77868. var axis = coordSys.getAxis(dimName);
  77869. var axisModel = axis.model;
  77870. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  77871. // Restrict range.
  77872. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  77873. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  77874. minMax = sliderMove(
  77875. 0, minMax.slice(), axis.scale.getExtent(), 0,
  77876. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  77877. );
  77878. }
  77879. dataZoomModel && (snapshot[dataZoomModel.id] = {
  77880. dataZoomId: dataZoomModel.id,
  77881. startValue: minMax[0],
  77882. endValue: minMax[1]
  77883. });
  77884. }
  77885. function findDataZoom(dimName, axisModel, ecModel) {
  77886. var found;
  77887. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  77888. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  77889. has && (found = dzModel);
  77890. });
  77891. return found;
  77892. }
  77893. };
  77894. /**
  77895. * @private
  77896. */
  77897. proto$6._dispatchZoomAction = function (snapshot) {
  77898. var batch = [];
  77899. // Convert from hash map to array.
  77900. each$28(snapshot, function (batchItem, dataZoomId) {
  77901. batch.push(clone(batchItem));
  77902. });
  77903. batch.length && this.api.dispatchAction({
  77904. type: 'dataZoom',
  77905. from: this.uid,
  77906. batch: batch
  77907. });
  77908. };
  77909. function retrieveAxisSetting(option) {
  77910. var setting = {};
  77911. // Compatible with previous setting: null => all axis, false => no axis.
  77912. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  77913. setting[name] = option[name];
  77914. setting[name] == null && (setting[name] = 'all');
  77915. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  77916. });
  77917. return setting;
  77918. }
  77919. function updateBackBtnStatus(featureModel, ecModel) {
  77920. featureModel.setIconStatus(
  77921. 'back',
  77922. count(ecModel) > 1 ? 'emphasis' : 'normal'
  77923. );
  77924. }
  77925. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  77926. var zoomActive = view._isZoomActive;
  77927. if (payload && payload.type === 'takeGlobalCursor') {
  77928. zoomActive = payload.key === 'dataZoomSelect'
  77929. ? payload.dataZoomSelectActive : false;
  77930. }
  77931. view._isZoomActive = zoomActive;
  77932. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  77933. var brushTargetManager = new BrushTargetManager(
  77934. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  77935. );
  77936. view._brushController
  77937. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  77938. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  77939. ? 'lineX'
  77940. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  77941. ? 'lineY'
  77942. : 'rect';
  77943. }))
  77944. .enableBrush(
  77945. zoomActive
  77946. ? {
  77947. brushType: 'auto',
  77948. brushStyle: {
  77949. // FIXME user customized?
  77950. lineWidth: 0,
  77951. fill: 'rgba(0,0,0,0.2)'
  77952. }
  77953. }
  77954. : false
  77955. );
  77956. }
  77957. register$1('dataZoom', DataZoom);
  77958. // Create special dataZoom option for select
  77959. // FIXME consider the case of merge option, where axes options are not exists.
  77960. registerPreprocessor(function (option) {
  77961. if (!option) {
  77962. return;
  77963. }
  77964. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  77965. if (!isArray(dataZoomOpts)) {
  77966. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  77967. }
  77968. var toolboxOpt = option.toolbox;
  77969. if (toolboxOpt) {
  77970. // Assume there is only one toolbox
  77971. if (isArray(toolboxOpt)) {
  77972. toolboxOpt = toolboxOpt[0];
  77973. }
  77974. if (toolboxOpt && toolboxOpt.feature) {
  77975. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  77976. // FIXME: If add dataZoom when setOption in merge mode,
  77977. // no axis info to be added. See `test/dataZoom-extreme.html`
  77978. addForAxis('xAxis', dataZoomOpt);
  77979. addForAxis('yAxis', dataZoomOpt);
  77980. }
  77981. }
  77982. function addForAxis(axisName, dataZoomOpt) {
  77983. if (!dataZoomOpt) {
  77984. return;
  77985. }
  77986. // Try not to modify model, because it is not merged yet.
  77987. var axisIndicesName = axisName + 'Index';
  77988. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  77989. if (givenAxisIndices != null
  77990. && givenAxisIndices !== 'all'
  77991. && !isArray(givenAxisIndices)
  77992. ) {
  77993. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  77994. }
  77995. forEachComponent(axisName, function (axisOpt, axisIndex) {
  77996. if (givenAxisIndices != null
  77997. && givenAxisIndices !== 'all'
  77998. && indexOf(givenAxisIndices, axisIndex) === -1
  77999. ) {
  78000. return;
  78001. }
  78002. var newOpt = {
  78003. type: 'select',
  78004. $fromToolbox: true,
  78005. // Id for merge mapping.
  78006. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  78007. };
  78008. // FIXME
  78009. // Only support one axis now.
  78010. newOpt[axisIndicesName] = axisIndex;
  78011. dataZoomOpts.push(newOpt);
  78012. });
  78013. }
  78014. function forEachComponent(mainType, cb) {
  78015. var opts = option[mainType];
  78016. if (!isArray(opts)) {
  78017. opts = opts ? [opts] : [];
  78018. }
  78019. each$28(opts, cb);
  78020. }
  78021. });
  78022. /*
  78023. * Licensed to the Apache Software Foundation (ASF) under one
  78024. * or more contributor license agreements. See the NOTICE file
  78025. * distributed with this work for additional information
  78026. * regarding copyright ownership. The ASF licenses this file
  78027. * to you under the Apache License, Version 2.0 (the
  78028. * "License"); you may not use this file except in compliance
  78029. * with the License. You may obtain a copy of the License at
  78030. *
  78031. * http://www.apache.org/licenses/LICENSE-2.0
  78032. *
  78033. * Unless required by applicable law or agreed to in writing,
  78034. * software distributed under the License is distributed on an
  78035. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78036. * KIND, either express or implied. See the License for the
  78037. * specific language governing permissions and limitations
  78038. * under the License.
  78039. */
  78040. var restoreLang = lang.toolbox.restore;
  78041. function Restore(model) {
  78042. this.model = model;
  78043. }
  78044. Restore.defaultOption = {
  78045. show: true,
  78046. /* eslint-disable */
  78047. 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',
  78048. /* eslint-enable */
  78049. title: restoreLang.title
  78050. };
  78051. var proto$7 = Restore.prototype;
  78052. proto$7.onclick = function (ecModel, api, type) {
  78053. clear$1(ecModel);
  78054. api.dispatchAction({
  78055. type: 'restore',
  78056. from: this.uid
  78057. });
  78058. };
  78059. register$1('restore', Restore);
  78060. registerAction(
  78061. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  78062. function (payload, ecModel) {
  78063. ecModel.resetOption('recreate');
  78064. }
  78065. );
  78066. /*
  78067. * Licensed to the Apache Software Foundation (ASF) under one
  78068. * or more contributor license agreements. See the NOTICE file
  78069. * distributed with this work for additional information
  78070. * regarding copyright ownership. The ASF licenses this file
  78071. * to you under the Apache License, Version 2.0 (the
  78072. * "License"); you may not use this file except in compliance
  78073. * with the License. You may obtain a copy of the License at
  78074. *
  78075. * http://www.apache.org/licenses/LICENSE-2.0
  78076. *
  78077. * Unless required by applicable law or agreed to in writing,
  78078. * software distributed under the License is distributed on an
  78079. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  78080. * KIND, either express or implied. See the License for the
  78081. * specific language governing permissions and limitations
  78082. * under the License.
  78083. */
  78084. var urn = 'urn:schemas-microsoft-com:vml';
  78085. var win = typeof window === 'undefined' ? null : window;
  78086. var vmlInited = false;
  78087. var doc = win && win.document;
  78088. function createNode(tagName) {
  78089. return doCreateNode(tagName);
  78090. }
  78091. // Avoid assign to an exported variable, for transforming to cjs.
  78092. var doCreateNode;
  78093. if (doc && !env$1.canvasSupported) {
  78094. try {
  78095. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  78096. doCreateNode = function (tagName) {
  78097. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  78098. };
  78099. }
  78100. catch (e) {
  78101. doCreateNode = function (tagName) {
  78102. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  78103. };
  78104. }
  78105. }
  78106. // From raphael
  78107. function initVML() {
  78108. if (vmlInited || !doc) {
  78109. return;
  78110. }
  78111. vmlInited = true;
  78112. var styleSheets = doc.styleSheets;
  78113. if (styleSheets.length < 31) {
  78114. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  78115. }
  78116. else {
  78117. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  78118. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  78119. }
  78120. }
  78121. // http://www.w3.org/TR/NOTE-VML
  78122. // TODO Use proxy like svg instead of overwrite brush methods
  78123. var CMD$3 = PathProxy.CMD;
  78124. var round$4 = Math.round;
  78125. var sqrt = Math.sqrt;
  78126. var abs$1 = Math.abs;
  78127. var cos = Math.cos;
  78128. var sin = Math.sin;
  78129. var mathMax$8 = Math.max;
  78130. if (!env$1.canvasSupported) {
  78131. var comma = ',';
  78132. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  78133. var Z = 21600;
  78134. var Z2 = Z / 2;
  78135. var ZLEVEL_BASE = 100000;
  78136. var Z_BASE$1 = 1000;
  78137. var initRootElStyle = function (el) {
  78138. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  78139. el.coordsize = Z + ',' + Z;
  78140. el.coordorigin = '0,0';
  78141. };
  78142. var encodeHtmlAttribute = function (s) {
  78143. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  78144. };
  78145. var rgb2Str = function (r, g, b) {
  78146. return 'rgb(' + [r, g, b].join(',') + ')';
  78147. };
  78148. var append = function (parent, child) {
  78149. if (child && parent && child.parentNode !== parent) {
  78150. parent.appendChild(child);
  78151. }
  78152. };
  78153. var remove = function (parent, child) {
  78154. if (child && parent && child.parentNode === parent) {
  78155. parent.removeChild(child);
  78156. }
  78157. };
  78158. var getZIndex = function (zlevel, z, z2) {
  78159. // z 的取值范围为 [0, 1000]
  78160. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  78161. };
  78162. var parsePercent$3 = function (value, maxValue) {
  78163. if (typeof value === 'string') {
  78164. if (value.lastIndexOf('%') >= 0) {
  78165. return parseFloat(value) / 100 * maxValue;
  78166. }
  78167. return parseFloat(value);
  78168. }
  78169. return value;
  78170. };
  78171. /***************************************************
  78172. * PATH
  78173. **************************************************/
  78174. var setColorAndOpacity = function (el, color, opacity) {
  78175. var colorArr = parse(color);
  78176. opacity = +opacity;
  78177. if (isNaN(opacity)) {
  78178. opacity = 1;
  78179. }
  78180. if (colorArr) {
  78181. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  78182. el.opacity = opacity * colorArr[3];
  78183. }
  78184. };
  78185. var getColorAndAlpha = function (color) {
  78186. var colorArr = parse(color);
  78187. return [
  78188. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  78189. colorArr[3]
  78190. ];
  78191. };
  78192. var updateFillNode = function (el, style, zrEl) {
  78193. // TODO pattern
  78194. var fill = style.fill;
  78195. if (fill != null) {
  78196. // Modified from excanvas
  78197. if (fill instanceof Gradient) {
  78198. var gradientType;
  78199. var angle = 0;
  78200. var focus = [0, 0];
  78201. // additional offset
  78202. var shift = 0;
  78203. // scale factor for offset
  78204. var expansion = 1;
  78205. var rect = zrEl.getBoundingRect();
  78206. var rectWidth = rect.width;
  78207. var rectHeight = rect.height;
  78208. if (fill.type === 'linear') {
  78209. gradientType = 'gradient';
  78210. var transform = zrEl.transform;
  78211. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  78212. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  78213. if (transform) {
  78214. applyTransform(p0, p0, transform);
  78215. applyTransform(p1, p1, transform);
  78216. }
  78217. var dx = p1[0] - p0[0];
  78218. var dy = p1[1] - p0[1];
  78219. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  78220. // The angle should be a non-negative number.
  78221. if (angle < 0) {
  78222. angle += 360;
  78223. }
  78224. // Very small angles produce an unexpected result because they are
  78225. // converted to a scientific notation string.
  78226. if (angle < 1e-6) {
  78227. angle = 0;
  78228. }
  78229. }
  78230. else {
  78231. gradientType = 'gradientradial';
  78232. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  78233. var transform = zrEl.transform;
  78234. var scale$$1 = zrEl.scale;
  78235. var width = rectWidth;
  78236. var height = rectHeight;
  78237. focus = [
  78238. // Percent in bounding rect
  78239. (p0[0] - rect.x) / width,
  78240. (p0[1] - rect.y) / height
  78241. ];
  78242. if (transform) {
  78243. applyTransform(p0, p0, transform);
  78244. }
  78245. width /= scale$$1[0] * Z;
  78246. height /= scale$$1[1] * Z;
  78247. var dimension = mathMax$8(width, height);
  78248. shift = 2 * 0 / dimension;
  78249. expansion = 2 * fill.r / dimension - shift;
  78250. }
  78251. // We need to sort the color stops in ascending order by offset,
  78252. // otherwise IE won't interpret it correctly.
  78253. var stops = fill.colorStops.slice();
  78254. stops.sort(function (cs1, cs2) {
  78255. return cs1.offset - cs2.offset;
  78256. });
  78257. var length$$1 = stops.length;
  78258. // Color and alpha list of first and last stop
  78259. var colorAndAlphaList = [];
  78260. var colors = [];
  78261. for (var i = 0; i < length$$1; i++) {
  78262. var stop = stops[i];
  78263. var colorAndAlpha = getColorAndAlpha(stop.color);
  78264. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  78265. if (i === 0 || i === length$$1 - 1) {
  78266. colorAndAlphaList.push(colorAndAlpha);
  78267. }
  78268. }
  78269. if (length$$1 >= 2) {
  78270. var color1 = colorAndAlphaList[0][0];
  78271. var color2 = colorAndAlphaList[1][0];
  78272. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  78273. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  78274. el.type = gradientType;
  78275. el.method = 'none';
  78276. el.focus = '100%';
  78277. el.angle = angle;
  78278. el.color = color1;
  78279. el.color2 = color2;
  78280. el.colors = colors.join(',');
  78281. // When colors attribute is used, the meanings of opacity and o:opacity2
  78282. // are reversed.
  78283. el.opacity = opacity2;
  78284. // FIXME g_o_:opacity ?
  78285. el.opacity2 = opacity1;
  78286. }
  78287. if (gradientType === 'radial') {
  78288. el.focusposition = focus.join(',');
  78289. }
  78290. }
  78291. else {
  78292. // FIXME Change from Gradient fill to color fill
  78293. setColorAndOpacity(el, fill, style.opacity);
  78294. }
  78295. }
  78296. };
  78297. var updateStrokeNode = function (el, style) {
  78298. // if (style.lineJoin != null) {
  78299. // el.joinstyle = style.lineJoin;
  78300. // }
  78301. // if (style.miterLimit != null) {
  78302. // el.miterlimit = style.miterLimit * Z;
  78303. // }
  78304. // if (style.lineCap != null) {
  78305. // el.endcap = style.lineCap;
  78306. // }
  78307. if (style.lineDash != null) {
  78308. el.dashstyle = style.lineDash.join(' ');
  78309. }
  78310. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  78311. setColorAndOpacity(el, style.stroke, style.opacity);
  78312. }
  78313. };
  78314. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  78315. var isFill = type === 'fill';
  78316. var el = vmlEl.getElementsByTagName(type)[0];
  78317. // Stroke must have lineWidth
  78318. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  78319. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  78320. // FIXME Remove before updating, or set `colors` will throw error
  78321. if (style[type] instanceof Gradient) {
  78322. remove(vmlEl, el);
  78323. }
  78324. if (!el) {
  78325. el = createNode(type);
  78326. }
  78327. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  78328. append(vmlEl, el);
  78329. }
  78330. else {
  78331. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  78332. remove(vmlEl, el);
  78333. }
  78334. };
  78335. var points$3 = [[], [], []];
  78336. var pathDataToString = function (path, m) {
  78337. var M = CMD$3.M;
  78338. var C = CMD$3.C;
  78339. var L = CMD$3.L;
  78340. var A = CMD$3.A;
  78341. var Q = CMD$3.Q;
  78342. var str = [];
  78343. var nPoint;
  78344. var cmdStr;
  78345. var cmd;
  78346. var i;
  78347. var xi;
  78348. var yi;
  78349. var data = path.data;
  78350. var dataLength = path.len();
  78351. for (i = 0; i < dataLength;) {
  78352. cmd = data[i++];
  78353. cmdStr = '';
  78354. nPoint = 0;
  78355. switch (cmd) {
  78356. case M:
  78357. cmdStr = ' m ';
  78358. nPoint = 1;
  78359. xi = data[i++];
  78360. yi = data[i++];
  78361. points$3[0][0] = xi;
  78362. points$3[0][1] = yi;
  78363. break;
  78364. case L:
  78365. cmdStr = ' l ';
  78366. nPoint = 1;
  78367. xi = data[i++];
  78368. yi = data[i++];
  78369. points$3[0][0] = xi;
  78370. points$3[0][1] = yi;
  78371. break;
  78372. case Q:
  78373. case C:
  78374. cmdStr = ' c ';
  78375. nPoint = 3;
  78376. var x1 = data[i++];
  78377. var y1 = data[i++];
  78378. var x2 = data[i++];
  78379. var y2 = data[i++];
  78380. var x3;
  78381. var y3;
  78382. if (cmd === Q) {
  78383. // Convert quadratic to cubic using degree elevation
  78384. x3 = x2;
  78385. y3 = y2;
  78386. x2 = (x2 + 2 * x1) / 3;
  78387. y2 = (y2 + 2 * y1) / 3;
  78388. x1 = (xi + 2 * x1) / 3;
  78389. y1 = (yi + 2 * y1) / 3;
  78390. }
  78391. else {
  78392. x3 = data[i++];
  78393. y3 = data[i++];
  78394. }
  78395. points$3[0][0] = x1;
  78396. points$3[0][1] = y1;
  78397. points$3[1][0] = x2;
  78398. points$3[1][1] = y2;
  78399. points$3[2][0] = x3;
  78400. points$3[2][1] = y3;
  78401. xi = x3;
  78402. yi = y3;
  78403. break;
  78404. case A:
  78405. var x = 0;
  78406. var y = 0;
  78407. var sx = 1;
  78408. var sy = 1;
  78409. var angle = 0;
  78410. if (m) {
  78411. // Extract SRT from matrix
  78412. x = m[4];
  78413. y = m[5];
  78414. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  78415. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  78416. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  78417. }
  78418. var cx = data[i++];
  78419. var cy = data[i++];
  78420. var rx = data[i++];
  78421. var ry = data[i++];
  78422. var startAngle = data[i++] + angle;
  78423. var endAngle = data[i++] + startAngle + angle;
  78424. // FIXME
  78425. // var psi = data[i++];
  78426. i++;
  78427. var clockwise = data[i++];
  78428. var x0 = cx + cos(startAngle) * rx;
  78429. var y0 = cy + sin(startAngle) * ry;
  78430. var x1 = cx + cos(endAngle) * rx;
  78431. var y1 = cy + sin(endAngle) * ry;
  78432. var type = clockwise ? ' wa ' : ' at ';
  78433. if (Math.abs(x0 - x1) < 1e-4) {
  78434. // IE won't render arches drawn counter clockwise if x0 == x1.
  78435. if (Math.abs(endAngle - startAngle) > 1e-2) {
  78436. // Offset x0 by 1/80 of a pixel. Use something
  78437. // that can be represented in binary
  78438. if (clockwise) {
  78439. x0 += 270 / Z;
  78440. }
  78441. }
  78442. else {
  78443. // Avoid case draw full circle
  78444. if (Math.abs(y0 - cy) < 1e-4) {
  78445. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  78446. y1 -= 270 / Z;
  78447. }
  78448. else {
  78449. y1 += 270 / Z;
  78450. }
  78451. }
  78452. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  78453. x1 += 270 / Z;
  78454. }
  78455. else {
  78456. x1 -= 270 / Z;
  78457. }
  78458. }
  78459. }
  78460. str.push(
  78461. type,
  78462. round$4(((cx - rx) * sx + x) * Z - Z2), comma,
  78463. round$4(((cy - ry) * sy + y) * Z - Z2), comma,
  78464. round$4(((cx + rx) * sx + x) * Z - Z2), comma,
  78465. round$4(((cy + ry) * sy + y) * Z - Z2), comma,
  78466. round$4((x0 * sx + x) * Z - Z2), comma,
  78467. round$4((y0 * sy + y) * Z - Z2), comma,
  78468. round$4((x1 * sx + x) * Z - Z2), comma,
  78469. round$4((y1 * sy + y) * Z - Z2)
  78470. );
  78471. xi = x1;
  78472. yi = y1;
  78473. break;
  78474. case CMD$3.R:
  78475. var p0 = points$3[0];
  78476. var p1 = points$3[1];
  78477. // x0, y0
  78478. p0[0] = data[i++];
  78479. p0[1] = data[i++];
  78480. // x1, y1
  78481. p1[0] = p0[0] + data[i++];
  78482. p1[1] = p0[1] + data[i++];
  78483. if (m) {
  78484. applyTransform(p0, p0, m);
  78485. applyTransform(p1, p1, m);
  78486. }
  78487. p0[0] = round$4(p0[0] * Z - Z2);
  78488. p1[0] = round$4(p1[0] * Z - Z2);
  78489. p0[1] = round$4(p0[1] * Z - Z2);
  78490. p1[1] = round$4(p1[1] * Z - Z2);
  78491. str.push(
  78492. // x0, y0
  78493. ' m ', p0[0], comma, p0[1],
  78494. // x1, y0
  78495. ' l ', p1[0], comma, p0[1],
  78496. // x1, y1
  78497. ' l ', p1[0], comma, p1[1],
  78498. // x0, y1
  78499. ' l ', p0[0], comma, p1[1]
  78500. );
  78501. break;
  78502. case CMD$3.Z:
  78503. // FIXME Update xi, yi
  78504. str.push(' x ');
  78505. }
  78506. if (nPoint > 0) {
  78507. str.push(cmdStr);
  78508. for (var k = 0; k < nPoint; k++) {
  78509. var p = points$3[k];
  78510. m && applyTransform(p, p, m);
  78511. // 不 round 会非常慢
  78512. str.push(
  78513. round$4(p[0] * Z - Z2), comma, round$4(p[1] * Z - Z2),
  78514. k < nPoint - 1 ? comma : ''
  78515. );
  78516. }
  78517. }
  78518. }
  78519. return str.join('');
  78520. };
  78521. // Rewrite the original path method
  78522. Path.prototype.brushVML = function (vmlRoot) {
  78523. var style = this.style;
  78524. var vmlEl = this._vmlEl;
  78525. if (!vmlEl) {
  78526. vmlEl = createNode('shape');
  78527. initRootElStyle(vmlEl);
  78528. this._vmlEl = vmlEl;
  78529. }
  78530. updateFillAndStroke(vmlEl, 'fill', style, this);
  78531. updateFillAndStroke(vmlEl, 'stroke', style, this);
  78532. var m = this.transform;
  78533. var needTransform = m != null;
  78534. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  78535. if (strokeEl) {
  78536. var lineWidth = style.lineWidth;
  78537. // Get the line scale.
  78538. // Determinant of this.m_ means how much the area is enlarged by the
  78539. // transformation. So its square root can be used as a scale factor
  78540. // for width.
  78541. if (needTransform && !style.strokeNoScale) {
  78542. var det = m[0] * m[3] - m[1] * m[2];
  78543. lineWidth *= sqrt(abs$1(det));
  78544. }
  78545. strokeEl.weight = lineWidth + 'px';
  78546. }
  78547. var path = this.path || (this.path = new PathProxy());
  78548. if (this.__dirtyPath) {
  78549. path.beginPath();
  78550. path.subPixelOptimize = false;
  78551. this.buildPath(path, this.shape);
  78552. path.toStatic();
  78553. this.__dirtyPath = false;
  78554. }
  78555. vmlEl.path = pathDataToString(path, this.transform);
  78556. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  78557. // Append to root
  78558. append(vmlRoot, vmlEl);
  78559. // Text
  78560. if (style.text != null) {
  78561. this.drawRectText(vmlRoot, this.getBoundingRect());
  78562. }
  78563. else {
  78564. this.removeRectText(vmlRoot);
  78565. }
  78566. };
  78567. Path.prototype.onRemove = function (vmlRoot) {
  78568. remove(vmlRoot, this._vmlEl);
  78569. this.removeRectText(vmlRoot);
  78570. };
  78571. Path.prototype.onAdd = function (vmlRoot) {
  78572. append(vmlRoot, this._vmlEl);
  78573. this.appendRectText(vmlRoot);
  78574. };
  78575. /***************************************************
  78576. * IMAGE
  78577. **************************************************/
  78578. var isImage = function (img) {
  78579. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  78580. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  78581. // return img instanceof Image;
  78582. };
  78583. // Rewrite the original path method
  78584. ZImage.prototype.brushVML = function (vmlRoot) {
  78585. var style = this.style;
  78586. var image = style.image;
  78587. // Image original width, height
  78588. var ow;
  78589. var oh;
  78590. if (isImage(image)) {
  78591. var src = image.src;
  78592. if (src === this._imageSrc) {
  78593. ow = this._imageWidth;
  78594. oh = this._imageHeight;
  78595. }
  78596. else {
  78597. var imageRuntimeStyle = image.runtimeStyle;
  78598. var oldRuntimeWidth = imageRuntimeStyle.width;
  78599. var oldRuntimeHeight = imageRuntimeStyle.height;
  78600. imageRuntimeStyle.width = 'auto';
  78601. imageRuntimeStyle.height = 'auto';
  78602. // get the original size
  78603. ow = image.width;
  78604. oh = image.height;
  78605. // and remove overides
  78606. imageRuntimeStyle.width = oldRuntimeWidth;
  78607. imageRuntimeStyle.height = oldRuntimeHeight;
  78608. // Caching image original width, height and src
  78609. this._imageSrc = src;
  78610. this._imageWidth = ow;
  78611. this._imageHeight = oh;
  78612. }
  78613. image = src;
  78614. }
  78615. else {
  78616. if (image === this._imageSrc) {
  78617. ow = this._imageWidth;
  78618. oh = this._imageHeight;
  78619. }
  78620. }
  78621. if (!image) {
  78622. return;
  78623. }
  78624. var x = style.x || 0;
  78625. var y = style.y || 0;
  78626. var dw = style.width;
  78627. var dh = style.height;
  78628. var sw = style.sWidth;
  78629. var sh = style.sHeight;
  78630. var sx = style.sx || 0;
  78631. var sy = style.sy || 0;
  78632. var hasCrop = sw && sh;
  78633. var vmlEl = this._vmlEl;
  78634. if (!vmlEl) {
  78635. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  78636. // vmlEl = vmlCore.createNode('group');
  78637. vmlEl = doc.createElement('div');
  78638. initRootElStyle(vmlEl);
  78639. this._vmlEl = vmlEl;
  78640. }
  78641. var vmlElStyle = vmlEl.style;
  78642. var hasRotation = false;
  78643. var m;
  78644. var scaleX = 1;
  78645. var scaleY = 1;
  78646. if (this.transform) {
  78647. m = this.transform;
  78648. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  78649. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  78650. hasRotation = m[1] || m[2];
  78651. }
  78652. if (hasRotation) {
  78653. // If filters are necessary (rotation exists), create them
  78654. // filters are bog-slow, so only create them if abbsolutely necessary
  78655. // The following check doesn't account for skews (which don't exist
  78656. // in the canvas spec (yet) anyway.
  78657. // From excanvas
  78658. var p0 = [x, y];
  78659. var p1 = [x + dw, y];
  78660. var p2 = [x, y + dh];
  78661. var p3 = [x + dw, y + dh];
  78662. applyTransform(p0, p0, m);
  78663. applyTransform(p1, p1, m);
  78664. applyTransform(p2, p2, m);
  78665. applyTransform(p3, p3, m);
  78666. var maxX = mathMax$8(p0[0], p1[0], p2[0], p3[0]);
  78667. var maxY = mathMax$8(p0[1], p1[1], p2[1], p3[1]);
  78668. var transformFilter = [];
  78669. transformFilter.push('M11=', m[0] / scaleX, comma,
  78670. 'M12=', m[2] / scaleY, comma,
  78671. 'M21=', m[1] / scaleX, comma,
  78672. 'M22=', m[3] / scaleY, comma,
  78673. 'Dx=', round$4(x * scaleX + m[4]), comma,
  78674. 'Dy=', round$4(y * scaleY + m[5]));
  78675. vmlElStyle.padding = '0 ' + round$4(maxX) + 'px ' + round$4(maxY) + 'px 0';
  78676. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  78677. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  78678. + transformFilter.join('') + ', SizingMethod=clip)';
  78679. }
  78680. else {
  78681. if (m) {
  78682. x = x * scaleX + m[4];
  78683. y = y * scaleY + m[5];
  78684. }
  78685. vmlElStyle.filter = '';
  78686. vmlElStyle.left = round$4(x) + 'px';
  78687. vmlElStyle.top = round$4(y) + 'px';
  78688. }
  78689. var imageEl = this._imageEl;
  78690. var cropEl = this._cropEl;
  78691. if (!imageEl) {
  78692. imageEl = doc.createElement('div');
  78693. this._imageEl = imageEl;
  78694. }
  78695. var imageELStyle = imageEl.style;
  78696. if (hasCrop) {
  78697. // Needs know image original width and height
  78698. if (!(ow && oh)) {
  78699. var tmpImage = new Image();
  78700. var self = this;
  78701. tmpImage.onload = function () {
  78702. tmpImage.onload = null;
  78703. ow = tmpImage.width;
  78704. oh = tmpImage.height;
  78705. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  78706. imageELStyle.width = round$4(scaleX * ow * dw / sw) + 'px';
  78707. imageELStyle.height = round$4(scaleY * oh * dh / sh) + 'px';
  78708. // Caching image original width, height and src
  78709. self._imageWidth = ow;
  78710. self._imageHeight = oh;
  78711. self._imageSrc = image;
  78712. };
  78713. tmpImage.src = image;
  78714. }
  78715. else {
  78716. imageELStyle.width = round$4(scaleX * ow * dw / sw) + 'px';
  78717. imageELStyle.height = round$4(scaleY * oh * dh / sh) + 'px';
  78718. }
  78719. if (!cropEl) {
  78720. cropEl = doc.createElement('div');
  78721. cropEl.style.overflow = 'hidden';
  78722. this._cropEl = cropEl;
  78723. }
  78724. var cropElStyle = cropEl.style;
  78725. cropElStyle.width = round$4((dw + sx * dw / sw) * scaleX);
  78726. cropElStyle.height = round$4((dh + sy * dh / sh) * scaleY);
  78727. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  78728. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  78729. if (!cropEl.parentNode) {
  78730. vmlEl.appendChild(cropEl);
  78731. }
  78732. if (imageEl.parentNode !== cropEl) {
  78733. cropEl.appendChild(imageEl);
  78734. }
  78735. }
  78736. else {
  78737. imageELStyle.width = round$4(scaleX * dw) + 'px';
  78738. imageELStyle.height = round$4(scaleY * dh) + 'px';
  78739. vmlEl.appendChild(imageEl);
  78740. if (cropEl && cropEl.parentNode) {
  78741. vmlEl.removeChild(cropEl);
  78742. this._cropEl = null;
  78743. }
  78744. }
  78745. var filterStr = '';
  78746. var alpha = style.opacity;
  78747. if (alpha < 1) {
  78748. filterStr += '.Alpha(opacity=' + round$4(alpha * 100) + ') ';
  78749. }
  78750. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  78751. imageELStyle.filter = filterStr;
  78752. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  78753. // Append to root
  78754. append(vmlRoot, vmlEl);
  78755. // Text
  78756. if (style.text != null) {
  78757. this.drawRectText(vmlRoot, this.getBoundingRect());
  78758. }
  78759. };
  78760. ZImage.prototype.onRemove = function (vmlRoot) {
  78761. remove(vmlRoot, this._vmlEl);
  78762. this._vmlEl = null;
  78763. this._cropEl = null;
  78764. this._imageEl = null;
  78765. this.removeRectText(vmlRoot);
  78766. };
  78767. ZImage.prototype.onAdd = function (vmlRoot) {
  78768. append(vmlRoot, this._vmlEl);
  78769. this.appendRectText(vmlRoot);
  78770. };
  78771. /***************************************************
  78772. * TEXT
  78773. **************************************************/
  78774. var DEFAULT_STYLE_NORMAL = 'normal';
  78775. var fontStyleCache = {};
  78776. var fontStyleCacheCount = 0;
  78777. var MAX_FONT_CACHE_SIZE = 100;
  78778. var fontEl = document.createElement('div');
  78779. var getFontStyle = function (fontString) {
  78780. var fontStyle = fontStyleCache[fontString];
  78781. if (!fontStyle) {
  78782. // Clear cache
  78783. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  78784. fontStyleCacheCount = 0;
  78785. fontStyleCache = {};
  78786. }
  78787. var style = fontEl.style;
  78788. var fontFamily;
  78789. try {
  78790. style.font = fontString;
  78791. fontFamily = style.fontFamily.split(',')[0];
  78792. }
  78793. catch (e) {
  78794. }
  78795. fontStyle = {
  78796. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  78797. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  78798. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  78799. size: parseFloat(style.fontSize || 12) | 0,
  78800. family: fontFamily || 'Microsoft YaHei'
  78801. };
  78802. fontStyleCache[fontString] = fontStyle;
  78803. fontStyleCacheCount++;
  78804. }
  78805. return fontStyle;
  78806. };
  78807. var textMeasureEl;
  78808. // Overwrite measure text method
  78809. $override$1('measureText', function (text, textFont) {
  78810. var doc$$1 = doc;
  78811. if (!textMeasureEl) {
  78812. textMeasureEl = doc$$1.createElement('div');
  78813. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  78814. + 'padding:0;margin:0;border:none;white-space:pre;';
  78815. doc.body.appendChild(textMeasureEl);
  78816. }
  78817. try {
  78818. textMeasureEl.style.font = textFont;
  78819. }
  78820. catch (ex) {
  78821. // Ignore failures to set to invalid font.
  78822. }
  78823. textMeasureEl.innerHTML = '';
  78824. // Don't use innerHTML or innerText because they allow markup/whitespace.
  78825. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  78826. return {
  78827. width: textMeasureEl.offsetWidth
  78828. };
  78829. });
  78830. var tmpRect$2 = new BoundingRect();
  78831. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  78832. var style = this.style;
  78833. // Optimize, avoid normalize every time.
  78834. this.__dirty && normalizeTextStyle(style, true);
  78835. var text = style.text;
  78836. // Convert to string
  78837. text != null && (text += '');
  78838. if (!text) {
  78839. return;
  78840. }
  78841. // Convert rich text to plain text. Rich text is not supported in
  78842. // IE8-, but tags in rich text template will be removed.
  78843. if (style.rich) {
  78844. var contentBlock = parseRichText(text, style);
  78845. text = [];
  78846. for (var i = 0; i < contentBlock.lines.length; i++) {
  78847. var tokens = contentBlock.lines[i].tokens;
  78848. var textLine = [];
  78849. for (var j = 0; j < tokens.length; j++) {
  78850. textLine.push(tokens[j].text);
  78851. }
  78852. text.push(textLine.join(''));
  78853. }
  78854. text = text.join('\n');
  78855. }
  78856. var x;
  78857. var y;
  78858. var align = style.textAlign;
  78859. var verticalAlign = style.textVerticalAlign;
  78860. var fontStyle = getFontStyle(style.font);
  78861. // FIXME encodeHtmlAttribute ?
  78862. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  78863. + fontStyle.size + 'px "' + fontStyle.family + '"';
  78864. textRect = textRect || getBoundingRect(
  78865. text, font, align, verticalAlign, style.textPadding, style.textLineHeight
  78866. );
  78867. // Transform rect to view space
  78868. var m = this.transform;
  78869. // Ignore transform for text in other element
  78870. if (m && !fromTextEl) {
  78871. tmpRect$2.copy(rect);
  78872. tmpRect$2.applyTransform(m);
  78873. rect = tmpRect$2;
  78874. }
  78875. if (!fromTextEl) {
  78876. var textPosition = style.textPosition;
  78877. var distance$$1 = style.textDistance;
  78878. // Text position represented by coord
  78879. if (textPosition instanceof Array) {
  78880. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  78881. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  78882. align = align || 'left';
  78883. }
  78884. else {
  78885. var res = adjustTextPositionOnRect(
  78886. textPosition, rect, distance$$1
  78887. );
  78888. x = res.x;
  78889. y = res.y;
  78890. // Default align and baseline when has textPosition
  78891. align = align || res.textAlign;
  78892. verticalAlign = verticalAlign || res.textVerticalAlign;
  78893. }
  78894. }
  78895. else {
  78896. x = rect.x;
  78897. y = rect.y;
  78898. }
  78899. x = adjustTextX(x, textRect.width, align);
  78900. y = adjustTextY(y, textRect.height, verticalAlign);
  78901. // Force baseline 'middle'
  78902. y += textRect.height / 2;
  78903. // var fontSize = fontStyle.size;
  78904. // 1.75 is an arbitrary number, as there is no info about the text baseline
  78905. // switch (baseline) {
  78906. // case 'hanging':
  78907. // case 'top':
  78908. // y += fontSize / 1.75;
  78909. // break;
  78910. // case 'middle':
  78911. // break;
  78912. // default:
  78913. // // case null:
  78914. // // case 'alphabetic':
  78915. // // case 'ideographic':
  78916. // // case 'bottom':
  78917. // y -= fontSize / 2.25;
  78918. // break;
  78919. // }
  78920. // switch (align) {
  78921. // case 'left':
  78922. // break;
  78923. // case 'center':
  78924. // x -= textRect.width / 2;
  78925. // break;
  78926. // case 'right':
  78927. // x -= textRect.width;
  78928. // break;
  78929. // case 'end':
  78930. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  78931. // break;
  78932. // case 'start':
  78933. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  78934. // break;
  78935. // default:
  78936. // align = 'left';
  78937. // }
  78938. var createNode$$1 = createNode;
  78939. var textVmlEl = this._textVmlEl;
  78940. var pathEl;
  78941. var textPathEl;
  78942. var skewEl;
  78943. if (!textVmlEl) {
  78944. textVmlEl = createNode$$1('line');
  78945. pathEl = createNode$$1('path');
  78946. textPathEl = createNode$$1('textpath');
  78947. skewEl = createNode$$1('skew');
  78948. // FIXME Why here is not cammel case
  78949. // Align 'center' seems wrong
  78950. textPathEl.style['v-text-align'] = 'left';
  78951. initRootElStyle(textVmlEl);
  78952. pathEl.textpathok = true;
  78953. textPathEl.on = true;
  78954. textVmlEl.from = '0 0';
  78955. textVmlEl.to = '1000 0.05';
  78956. append(textVmlEl, skewEl);
  78957. append(textVmlEl, pathEl);
  78958. append(textVmlEl, textPathEl);
  78959. this._textVmlEl = textVmlEl;
  78960. }
  78961. else {
  78962. // 这里是在前面 appendChild 保证顺序的前提下
  78963. skewEl = textVmlEl.firstChild;
  78964. pathEl = skewEl.nextSibling;
  78965. textPathEl = pathEl.nextSibling;
  78966. }
  78967. var coords = [x, y];
  78968. var textVmlElStyle = textVmlEl.style;
  78969. // Ignore transform for text in other element
  78970. if (m && fromTextEl) {
  78971. applyTransform(coords, coords, m);
  78972. skewEl.on = true;
  78973. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma
  78974. + m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  78975. // Text position
  78976. skewEl.offset = (round$4(coords[0]) || 0) + ',' + (round$4(coords[1]) || 0);
  78977. // Left top point as origin
  78978. skewEl.origin = '0 0';
  78979. textVmlElStyle.left = '0px';
  78980. textVmlElStyle.top = '0px';
  78981. }
  78982. else {
  78983. skewEl.on = false;
  78984. textVmlElStyle.left = round$4(x) + 'px';
  78985. textVmlElStyle.top = round$4(y) + 'px';
  78986. }
  78987. textPathEl.string = encodeHtmlAttribute(text);
  78988. // TODO
  78989. try {
  78990. textPathEl.style.font = font;
  78991. }
  78992. // Error font format
  78993. catch (e) {}
  78994. updateFillAndStroke(textVmlEl, 'fill', {
  78995. fill: style.textFill,
  78996. opacity: style.opacity
  78997. }, this);
  78998. updateFillAndStroke(textVmlEl, 'stroke', {
  78999. stroke: style.textStroke,
  79000. opacity: style.opacity,
  79001. lineDash: style.lineDash
  79002. }, this);
  79003. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  79004. // Attached to root
  79005. append(vmlRoot, textVmlEl);
  79006. };
  79007. var removeRectText = function (vmlRoot) {
  79008. remove(vmlRoot, this._textVmlEl);
  79009. this._textVmlEl = null;
  79010. };
  79011. var appendRectText = function (vmlRoot) {
  79012. append(vmlRoot, this._textVmlEl);
  79013. };
  79014. var list = [RectText, Displayable, ZImage, Path, Text];
  79015. // In case Displayable has been mixed in RectText
  79016. for (var i$3 = 0; i$3 < list.length; i$3++) {
  79017. var proto$8 = list[i$3].prototype;
  79018. proto$8.drawRectText = drawRectText;
  79019. proto$8.removeRectText = removeRectText;
  79020. proto$8.appendRectText = appendRectText;
  79021. }
  79022. Text.prototype.brushVML = function (vmlRoot) {
  79023. var style = this.style;
  79024. if (style.text != null) {
  79025. this.drawRectText(vmlRoot, {
  79026. x: style.x || 0, y: style.y || 0,
  79027. width: 0, height: 0
  79028. }, this.getBoundingRect(), true);
  79029. }
  79030. else {
  79031. this.removeRectText(vmlRoot);
  79032. }
  79033. };
  79034. Text.prototype.onRemove = function (vmlRoot) {
  79035. this.removeRectText(vmlRoot);
  79036. };
  79037. Text.prototype.onAdd = function (vmlRoot) {
  79038. this.appendRectText(vmlRoot);
  79039. };
  79040. }
  79041. /**
  79042. * VML Painter.
  79043. *
  79044. * @module zrender/vml/Painter
  79045. */
  79046. function parseInt10$1(val) {
  79047. return parseInt(val, 10);
  79048. }
  79049. /**
  79050. * @alias module:zrender/vml/Painter
  79051. */
  79052. function VMLPainter(root, storage) {
  79053. initVML();
  79054. this.root = root;
  79055. this.storage = storage;
  79056. var vmlViewport = document.createElement('div');
  79057. var vmlRoot = document.createElement('div');
  79058. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  79059. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  79060. root.appendChild(vmlViewport);
  79061. this._vmlRoot = vmlRoot;
  79062. this._vmlViewport = vmlViewport;
  79063. this.resize();
  79064. // Modify storage
  79065. var oldDelFromStorage = storage.delFromStorage;
  79066. var oldAddToStorage = storage.addToStorage;
  79067. storage.delFromStorage = function (el) {
  79068. oldDelFromStorage.call(storage, el);
  79069. if (el) {
  79070. el.onRemove && el.onRemove(vmlRoot);
  79071. }
  79072. };
  79073. storage.addToStorage = function (el) {
  79074. // Displayable already has a vml node
  79075. el.onAdd && el.onAdd(vmlRoot);
  79076. oldAddToStorage.call(storage, el);
  79077. };
  79078. this._firstPaint = true;
  79079. }
  79080. VMLPainter.prototype = {
  79081. constructor: VMLPainter,
  79082. getType: function () {
  79083. return 'vml';
  79084. },
  79085. /**
  79086. * @return {HTMLDivElement}
  79087. */
  79088. getViewportRoot: function () {
  79089. return this._vmlViewport;
  79090. },
  79091. getViewportRootOffset: function () {
  79092. var viewportRoot = this.getViewportRoot();
  79093. if (viewportRoot) {
  79094. return {
  79095. offsetLeft: viewportRoot.offsetLeft || 0,
  79096. offsetTop: viewportRoot.offsetTop || 0
  79097. };
  79098. }
  79099. },
  79100. /**
  79101. * 刷新
  79102. */
  79103. refresh: function () {
  79104. var list = this.storage.getDisplayList(true, true);
  79105. this._paintList(list);
  79106. },
  79107. _paintList: function (list) {
  79108. var vmlRoot = this._vmlRoot;
  79109. for (var i = 0; i < list.length; i++) {
  79110. var el = list[i];
  79111. if (el.invisible || el.ignore) {
  79112. if (!el.__alreadyNotVisible) {
  79113. el.onRemove(vmlRoot);
  79114. }
  79115. // Set as already invisible
  79116. el.__alreadyNotVisible = true;
  79117. }
  79118. else {
  79119. if (el.__alreadyNotVisible) {
  79120. el.onAdd(vmlRoot);
  79121. }
  79122. el.__alreadyNotVisible = false;
  79123. if (el.__dirty) {
  79124. el.beforeBrush && el.beforeBrush();
  79125. (el.brushVML || el.brush).call(el, vmlRoot);
  79126. el.afterBrush && el.afterBrush();
  79127. }
  79128. }
  79129. el.__dirty = false;
  79130. }
  79131. if (this._firstPaint) {
  79132. // Detached from document at first time
  79133. // to avoid page refreshing too many times
  79134. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  79135. this._vmlViewport.appendChild(vmlRoot);
  79136. this._firstPaint = false;
  79137. }
  79138. },
  79139. resize: function (width, height) {
  79140. var width = width == null ? this._getWidth() : width;
  79141. var height = height == null ? this._getHeight() : height;
  79142. if (this._width !== width || this._height !== height) {
  79143. this._width = width;
  79144. this._height = height;
  79145. var vmlViewportStyle = this._vmlViewport.style;
  79146. vmlViewportStyle.width = width + 'px';
  79147. vmlViewportStyle.height = height + 'px';
  79148. }
  79149. },
  79150. dispose: function () {
  79151. this.root.innerHTML = '';
  79152. this._vmlRoot =
  79153. this._vmlViewport =
  79154. this.storage = null;
  79155. },
  79156. getWidth: function () {
  79157. return this._width;
  79158. },
  79159. getHeight: function () {
  79160. return this._height;
  79161. },
  79162. clear: function () {
  79163. if (this._vmlViewport) {
  79164. this.root.removeChild(this._vmlViewport);
  79165. }
  79166. },
  79167. _getWidth: function () {
  79168. var root = this.root;
  79169. var stl = root.currentStyle;
  79170. return ((root.clientWidth || parseInt10$1(stl.width))
  79171. - parseInt10$1(stl.paddingLeft)
  79172. - parseInt10$1(stl.paddingRight)) | 0;
  79173. },
  79174. _getHeight: function () {
  79175. var root = this.root;
  79176. var stl = root.currentStyle;
  79177. return ((root.clientHeight || parseInt10$1(stl.height))
  79178. - parseInt10$1(stl.paddingTop)
  79179. - parseInt10$1(stl.paddingBottom)) | 0;
  79180. }
  79181. };
  79182. // Not supported methods
  79183. function createMethodNotSupport(method) {
  79184. return function () {
  79185. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  79186. };
  79187. }
  79188. // Unsupported methods
  79189. each$1([
  79190. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  79191. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  79192. ], function (name) {
  79193. VMLPainter.prototype[name] = createMethodNotSupport(name);
  79194. });
  79195. registerPainter('vml', VMLPainter);
  79196. var svgURI = 'http://www.w3.org/2000/svg';
  79197. function createElement(name) {
  79198. return document.createElementNS(svgURI, name);
  79199. }
  79200. // TODO
  79201. // 1. shadow
  79202. // 2. Image: sx, sy, sw, sh
  79203. var CMD$4 = PathProxy.CMD;
  79204. var arrayJoin = Array.prototype.join;
  79205. var NONE = 'none';
  79206. var mathRound = Math.round;
  79207. var mathSin$3 = Math.sin;
  79208. var mathCos$3 = Math.cos;
  79209. var PI$5 = Math.PI;
  79210. var PI2$7 = Math.PI * 2;
  79211. var degree = 180 / PI$5;
  79212. var EPSILON$4 = 1e-4;
  79213. function round4(val) {
  79214. return mathRound(val * 1e4) / 1e4;
  79215. }
  79216. function isAroundZero$1(val) {
  79217. return val < EPSILON$4 && val > -EPSILON$4;
  79218. }
  79219. function pathHasFill(style, isText) {
  79220. var fill = isText ? style.textFill : style.fill;
  79221. return fill != null && fill !== NONE;
  79222. }
  79223. function pathHasStroke(style, isText) {
  79224. var stroke = isText ? style.textStroke : style.stroke;
  79225. return stroke != null && stroke !== NONE;
  79226. }
  79227. function setTransform(svgEl, m) {
  79228. if (m) {
  79229. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  79230. }
  79231. }
  79232. function attr(el, key, val) {
  79233. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  79234. // Don't set attribute for gradient, since it need new dom nodes
  79235. el.setAttribute(key, val);
  79236. }
  79237. }
  79238. function attrXLink(el, key, val) {
  79239. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  79240. }
  79241. function bindStyle(svgEl, style, isText, el) {
  79242. if (pathHasFill(style, isText)) {
  79243. var fill = isText ? style.textFill : style.fill;
  79244. fill = fill === 'transparent' ? NONE : fill;
  79245. /**
  79246. * FIXME:
  79247. * This is a temporary fix for Chrome's clipping bug
  79248. * that happens when a clip-path is referring another one.
  79249. * This fix should be used before Chrome's bug is fixed.
  79250. * For an element that has clip-path, and fill is none,
  79251. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  79252. * Otherwise, it will show black fill color.
  79253. * 0.002 is used because this won't work for alpha values smaller
  79254. * than 0.002.
  79255. *
  79256. * See
  79257. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  79258. * for more information.
  79259. */
  79260. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  79261. fill = 'rgba(0, 0, 0, 0.002)';
  79262. }
  79263. attr(svgEl, 'fill', fill);
  79264. attr(svgEl, 'fill-opacity', style.fillOpacity != null ? style.fillOpacity * style.opacity : style.opacity);
  79265. }
  79266. else {
  79267. attr(svgEl, 'fill', NONE);
  79268. }
  79269. if (pathHasStroke(style, isText)) {
  79270. var stroke = isText ? style.textStroke : style.stroke;
  79271. stroke = stroke === 'transparent' ? NONE : stroke;
  79272. attr(svgEl, 'stroke', stroke);
  79273. var strokeWidth = isText
  79274. ? style.textStrokeWidth
  79275. : style.lineWidth;
  79276. var strokeScale = !isText && style.strokeNoScale
  79277. ? el.getLineScale()
  79278. : 1;
  79279. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  79280. // stroke then fill for text; fill then stroke for others
  79281. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  79282. attr(svgEl, 'stroke-opacity', style.strokeOpacity != null ? style.strokeOpacity : style.opacity);
  79283. var lineDash = style.lineDash;
  79284. if (lineDash) {
  79285. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  79286. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  79287. }
  79288. else {
  79289. attr(svgEl, 'stroke-dasharray', '');
  79290. }
  79291. // PENDING
  79292. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  79293. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  79294. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  79295. }
  79296. else {
  79297. attr(svgEl, 'stroke', NONE);
  79298. }
  79299. }
  79300. /***************************************************
  79301. * PATH
  79302. **************************************************/
  79303. function pathDataToString$1(path) {
  79304. var str = [];
  79305. var data = path.data;
  79306. var dataLength = path.len();
  79307. for (var i = 0; i < dataLength;) {
  79308. var cmd = data[i++];
  79309. var cmdStr = '';
  79310. var nData = 0;
  79311. switch (cmd) {
  79312. case CMD$4.M:
  79313. cmdStr = 'M';
  79314. nData = 2;
  79315. break;
  79316. case CMD$4.L:
  79317. cmdStr = 'L';
  79318. nData = 2;
  79319. break;
  79320. case CMD$4.Q:
  79321. cmdStr = 'Q';
  79322. nData = 4;
  79323. break;
  79324. case CMD$4.C:
  79325. cmdStr = 'C';
  79326. nData = 6;
  79327. break;
  79328. case CMD$4.A:
  79329. var cx = data[i++];
  79330. var cy = data[i++];
  79331. var rx = data[i++];
  79332. var ry = data[i++];
  79333. var theta = data[i++];
  79334. var dTheta = data[i++];
  79335. var psi = data[i++];
  79336. var clockwise = data[i++];
  79337. var dThetaPositive = Math.abs(dTheta);
  79338. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  79339. && !isAroundZero$1(dThetaPositive);
  79340. var large = false;
  79341. if (dThetaPositive >= PI2$7) {
  79342. large = true;
  79343. }
  79344. else if (isAroundZero$1(dThetaPositive)) {
  79345. large = false;
  79346. }
  79347. else {
  79348. large = (dTheta > -PI$5 && dTheta < 0 || dTheta > PI$5)
  79349. === !!clockwise;
  79350. }
  79351. var x0 = round4(cx + rx * mathCos$3(theta));
  79352. var y0 = round4(cy + ry * mathSin$3(theta));
  79353. // It will not draw if start point and end point are exactly the same
  79354. // We need to shift the end point with a small value
  79355. // FIXME A better way to draw circle ?
  79356. if (isCircle) {
  79357. if (clockwise) {
  79358. dTheta = PI2$7 - 1e-4;
  79359. }
  79360. else {
  79361. dTheta = -PI2$7 + 1e-4;
  79362. }
  79363. large = true;
  79364. if (i === 9) {
  79365. // Move to (x0, y0) only when CMD.A comes at the
  79366. // first position of a shape.
  79367. // For instance, when drawing a ring, CMD.A comes
  79368. // after CMD.M, so it's unnecessary to move to
  79369. // (x0, y0).
  79370. str.push('M', x0, y0);
  79371. }
  79372. }
  79373. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  79374. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  79375. // FIXME Ellipse
  79376. str.push('A', round4(rx), round4(ry),
  79377. mathRound(psi * degree), +large, +clockwise, x, y);
  79378. break;
  79379. case CMD$4.Z:
  79380. cmdStr = 'Z';
  79381. break;
  79382. case CMD$4.R:
  79383. var x = round4(data[i++]);
  79384. var y = round4(data[i++]);
  79385. var w = round4(data[i++]);
  79386. var h = round4(data[i++]);
  79387. str.push(
  79388. 'M', x, y,
  79389. 'L', x + w, y,
  79390. 'L', x + w, y + h,
  79391. 'L', x, y + h,
  79392. 'L', x, y
  79393. );
  79394. break;
  79395. }
  79396. cmdStr && str.push(cmdStr);
  79397. for (var j = 0; j < nData; j++) {
  79398. // PENDING With scale
  79399. str.push(round4(data[i++]));
  79400. }
  79401. }
  79402. return str.join(' ');
  79403. }
  79404. var svgPath = {};
  79405. svgPath.brush = function (el) {
  79406. var style = el.style;
  79407. var svgEl = el.__svgEl;
  79408. if (!svgEl) {
  79409. svgEl = createElement('path');
  79410. el.__svgEl = svgEl;
  79411. }
  79412. if (!el.path) {
  79413. el.createPathProxy();
  79414. }
  79415. var path = el.path;
  79416. if (el.__dirtyPath) {
  79417. path.beginPath();
  79418. path.subPixelOptimize = false;
  79419. el.buildPath(path, el.shape);
  79420. el.__dirtyPath = false;
  79421. var pathStr = pathDataToString$1(path);
  79422. if (pathStr.indexOf('NaN') < 0) {
  79423. // Ignore illegal path, which may happen such in out-of-range
  79424. // data in Calendar series.
  79425. attr(svgEl, 'd', pathStr);
  79426. }
  79427. }
  79428. bindStyle(svgEl, style, false, el);
  79429. setTransform(svgEl, el.transform);
  79430. if (style.text != null) {
  79431. svgTextDrawRectText(el, el.getBoundingRect());
  79432. }
  79433. };
  79434. /***************************************************
  79435. * IMAGE
  79436. **************************************************/
  79437. var svgImage = {};
  79438. svgImage.brush = function (el) {
  79439. var style = el.style;
  79440. var image = style.image;
  79441. if (image instanceof HTMLImageElement) {
  79442. var src = image.src;
  79443. image = src;
  79444. }
  79445. if (!image) {
  79446. return;
  79447. }
  79448. var x = style.x || 0;
  79449. var y = style.y || 0;
  79450. var dw = style.width;
  79451. var dh = style.height;
  79452. var svgEl = el.__svgEl;
  79453. if (!svgEl) {
  79454. svgEl = createElement('image');
  79455. el.__svgEl = svgEl;
  79456. }
  79457. if (image !== el.__imageSrc) {
  79458. attrXLink(svgEl, 'href', image);
  79459. // Caching image src
  79460. el.__imageSrc = image;
  79461. }
  79462. attr(svgEl, 'width', dw);
  79463. attr(svgEl, 'height', dh);
  79464. attr(svgEl, 'x', x);
  79465. attr(svgEl, 'y', y);
  79466. setTransform(svgEl, el.transform);
  79467. if (style.text != null) {
  79468. svgTextDrawRectText(el, el.getBoundingRect());
  79469. }
  79470. };
  79471. /***************************************************
  79472. * TEXT
  79473. **************************************************/
  79474. var svgText = {};
  79475. var tmpRect$3 = new BoundingRect();
  79476. var svgTextDrawRectText = function (el, rect, textRect) {
  79477. var style = el.style;
  79478. el.__dirty && normalizeTextStyle(style, true);
  79479. var text = style.text;
  79480. // Convert to string
  79481. if (text == null) {
  79482. // Draw no text only when text is set to null, but not ''
  79483. return;
  79484. }
  79485. else {
  79486. text += '';
  79487. }
  79488. var textSvgEl = el.__textSvgEl;
  79489. if (!textSvgEl) {
  79490. textSvgEl = createElement('text');
  79491. el.__textSvgEl = textSvgEl;
  79492. }
  79493. var x;
  79494. var y;
  79495. var textPosition = style.textPosition;
  79496. var distance = style.textDistance;
  79497. var align = style.textAlign || 'left';
  79498. if (typeof style.fontSize === 'number') {
  79499. style.fontSize += 'px';
  79500. }
  79501. var font = style.font
  79502. || [
  79503. style.fontStyle || '',
  79504. style.fontWeight || '',
  79505. style.fontSize || '',
  79506. style.fontFamily || ''
  79507. ].join(' ')
  79508. || DEFAULT_FONT$1;
  79509. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  79510. textRect = getBoundingRect(
  79511. text, font, align,
  79512. verticalAlign, style.textPadding, style.textLineHeight
  79513. );
  79514. var lineHeight = textRect.lineHeight;
  79515. // Text position represented by coord
  79516. if (textPosition instanceof Array) {
  79517. x = rect.x + textPosition[0];
  79518. y = rect.y + textPosition[1];
  79519. }
  79520. else {
  79521. var newPos = adjustTextPositionOnRect(
  79522. textPosition, rect, distance
  79523. );
  79524. x = newPos.x;
  79525. y = newPos.y;
  79526. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  79527. align = newPos.textAlign;
  79528. }
  79529. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  79530. if (font) {
  79531. textSvgEl.style.font = font;
  79532. }
  79533. var textPadding = style.textPadding;
  79534. // Make baseline top
  79535. attr(textSvgEl, 'x', x);
  79536. attr(textSvgEl, 'y', y);
  79537. bindStyle(textSvgEl, style, true, el);
  79538. if (el instanceof Text || el.style.transformText) {
  79539. // Transform text with element
  79540. setTransform(textSvgEl, el.transform);
  79541. }
  79542. else {
  79543. if (el.transform) {
  79544. tmpRect$3.copy(rect);
  79545. tmpRect$3.applyTransform(el.transform);
  79546. rect = tmpRect$3;
  79547. }
  79548. else {
  79549. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  79550. rect.x = pos[0];
  79551. rect.y = pos[1];
  79552. el.transform = identity(create$1());
  79553. }
  79554. // Text rotation, but no element transform
  79555. var origin = style.textOrigin;
  79556. if (origin === 'center') {
  79557. x = textRect.width / 2 + x;
  79558. y = textRect.height / 2 + y;
  79559. }
  79560. else if (origin) {
  79561. x = origin[0] + x;
  79562. y = origin[1] + y;
  79563. }
  79564. var rotate$$1 = -style.textRotation || 0;
  79565. var transform = create$1();
  79566. // Apply textRotate to element matrix
  79567. rotate(transform, transform, rotate$$1);
  79568. var pos = [el.transform[4], el.transform[5]];
  79569. translate(transform, transform, pos);
  79570. setTransform(textSvgEl, transform);
  79571. }
  79572. var textLines = text.split('\n');
  79573. var nTextLines = textLines.length;
  79574. var textAnchor = align;
  79575. // PENDING
  79576. if (textAnchor === 'left') {
  79577. textAnchor = 'start';
  79578. textPadding && (x += textPadding[3]);
  79579. }
  79580. else if (textAnchor === 'right') {
  79581. textAnchor = 'end';
  79582. textPadding && (x -= textPadding[1]);
  79583. }
  79584. else if (textAnchor === 'center') {
  79585. textAnchor = 'middle';
  79586. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  79587. }
  79588. var dy = 0;
  79589. if (verticalAlign === 'after-edge') {
  79590. dy = -textRect.height + lineHeight;
  79591. textPadding && (dy -= textPadding[2]);
  79592. }
  79593. else if (verticalAlign === 'middle') {
  79594. dy = (-textRect.height + lineHeight) / 2;
  79595. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  79596. }
  79597. else {
  79598. textPadding && (dy += textPadding[0]);
  79599. }
  79600. // Font may affect position of each tspan elements
  79601. if (el.__text !== text || el.__textFont !== font) {
  79602. var tspanList = el.__tspanList || [];
  79603. el.__tspanList = tspanList;
  79604. for (var i = 0; i < nTextLines; i++) {
  79605. // Using cached tspan elements
  79606. var tspan = tspanList[i];
  79607. if (!tspan) {
  79608. tspan = tspanList[i] = createElement('tspan');
  79609. textSvgEl.appendChild(tspan);
  79610. attr(tspan, 'alignment-baseline', verticalAlign);
  79611. attr(tspan, 'text-anchor', textAnchor);
  79612. }
  79613. else {
  79614. tspan.innerHTML = '';
  79615. }
  79616. attr(tspan, 'x', x);
  79617. attr(tspan, 'y', y + i * lineHeight + dy);
  79618. tspan.appendChild(document.createTextNode(textLines[i]));
  79619. }
  79620. // Remove unsed tspan elements
  79621. for (; i < tspanList.length; i++) {
  79622. textSvgEl.removeChild(tspanList[i]);
  79623. }
  79624. tspanList.length = nTextLines;
  79625. el.__text = text;
  79626. el.__textFont = font;
  79627. }
  79628. else if (el.__tspanList.length) {
  79629. // Update span x and y
  79630. var len = el.__tspanList.length;
  79631. for (var i = 0; i < len; ++i) {
  79632. var tspan = el.__tspanList[i];
  79633. if (tspan) {
  79634. attr(tspan, 'x', x);
  79635. attr(tspan, 'y', y + i * lineHeight + dy);
  79636. }
  79637. }
  79638. }
  79639. };
  79640. function getVerticalAlignForSvg(verticalAlign) {
  79641. if (verticalAlign === 'middle') {
  79642. return 'middle';
  79643. }
  79644. else if (verticalAlign === 'bottom') {
  79645. return 'after-edge';
  79646. }
  79647. else {
  79648. return 'hanging';
  79649. }
  79650. }
  79651. svgText.drawRectText = svgTextDrawRectText;
  79652. svgText.brush = function (el) {
  79653. var style = el.style;
  79654. if (style.text != null) {
  79655. // 强制设置 textPosition
  79656. style.textPosition = [0, 0];
  79657. svgTextDrawRectText(el, {
  79658. x: style.x || 0, y: style.y || 0,
  79659. width: 0, height: 0
  79660. }, el.getBoundingRect());
  79661. }
  79662. };
  79663. // Myers' Diff Algorithm
  79664. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  79665. function Diff() {}
  79666. Diff.prototype = {
  79667. diff: function (oldArr, newArr, equals) {
  79668. if (!equals) {
  79669. equals = function (a, b) {
  79670. return a === b;
  79671. };
  79672. }
  79673. this.equals = equals;
  79674. var self = this;
  79675. oldArr = oldArr.slice();
  79676. newArr = newArr.slice();
  79677. // Allow subclasses to massage the input prior to running
  79678. var newLen = newArr.length;
  79679. var oldLen = oldArr.length;
  79680. var editLength = 1;
  79681. var maxEditLength = newLen + oldLen;
  79682. var bestPath = [{ newPos: -1, components: [] }];
  79683. // Seed editLength = 0, i.e. the content starts with the same values
  79684. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  79685. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  79686. var indices = [];
  79687. for (var i = 0; i < newArr.length; i++) {
  79688. indices.push(i);
  79689. }
  79690. // Identity per the equality and tokenizer
  79691. return [{
  79692. indices: indices, count: newArr.length
  79693. }];
  79694. }
  79695. // Main worker method. checks all permutations of a given edit length for acceptance.
  79696. function execEditLength() {
  79697. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  79698. var basePath;
  79699. var addPath = bestPath[diagonalPath - 1];
  79700. var removePath = bestPath[diagonalPath + 1];
  79701. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  79702. if (addPath) {
  79703. // No one else is going to attempt to use this value, clear it
  79704. bestPath[diagonalPath - 1] = undefined;
  79705. }
  79706. var canAdd = addPath && addPath.newPos + 1 < newLen;
  79707. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  79708. if (!canAdd && !canRemove) {
  79709. // If this path is a terminal then prune
  79710. bestPath[diagonalPath] = undefined;
  79711. continue;
  79712. }
  79713. // Select the diagonal that we want to branch from. We select the prior
  79714. // path whose position in the new string is the farthest from the origin
  79715. // and does not pass the bounds of the diff graph
  79716. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  79717. basePath = clonePath(removePath);
  79718. self.pushComponent(basePath.components, undefined, true);
  79719. }
  79720. else {
  79721. basePath = addPath; // No need to clone, we've pulled it from the list
  79722. basePath.newPos++;
  79723. self.pushComponent(basePath.components, true, undefined);
  79724. }
  79725. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  79726. // If we have hit the end of both strings, then we are done
  79727. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  79728. return buildValues(self, basePath.components, newArr, oldArr);
  79729. }
  79730. else {
  79731. // Otherwise track this path as a potential candidate and continue.
  79732. bestPath[diagonalPath] = basePath;
  79733. }
  79734. }
  79735. editLength++;
  79736. }
  79737. while (editLength <= maxEditLength) {
  79738. var ret = execEditLength();
  79739. if (ret) {
  79740. return ret;
  79741. }
  79742. }
  79743. },
  79744. pushComponent: function (components, added, removed) {
  79745. var last = components[components.length - 1];
  79746. if (last && last.added === added && last.removed === removed) {
  79747. // We need to clone here as the component clone operation is just
  79748. // as shallow array clone
  79749. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  79750. }
  79751. else {
  79752. components.push({count: 1, added: added, removed: removed });
  79753. }
  79754. },
  79755. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  79756. var newLen = newArr.length;
  79757. var oldLen = oldArr.length;
  79758. var newPos = basePath.newPos;
  79759. var oldPos = newPos - diagonalPath;
  79760. var commonCount = 0;
  79761. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  79762. newPos++;
  79763. oldPos++;
  79764. commonCount++;
  79765. }
  79766. if (commonCount) {
  79767. basePath.components.push({count: commonCount});
  79768. }
  79769. basePath.newPos = newPos;
  79770. return oldPos;
  79771. },
  79772. tokenize: function (value) {
  79773. return value.slice();
  79774. },
  79775. join: function (value) {
  79776. return value.slice();
  79777. }
  79778. };
  79779. function buildValues(diff, components, newArr, oldArr) {
  79780. var componentPos = 0;
  79781. var componentLen = components.length;
  79782. var newPos = 0;
  79783. var oldPos = 0;
  79784. for (; componentPos < componentLen; componentPos++) {
  79785. var component = components[componentPos];
  79786. if (!component.removed) {
  79787. var indices = [];
  79788. for (var i = newPos; i < newPos + component.count; i++) {
  79789. indices.push(i);
  79790. }
  79791. component.indices = indices;
  79792. newPos += component.count;
  79793. // Common case
  79794. if (!component.added) {
  79795. oldPos += component.count;
  79796. }
  79797. }
  79798. else {
  79799. var indices = [];
  79800. for (var i = oldPos; i < oldPos + component.count; i++) {
  79801. indices.push(i);
  79802. }
  79803. component.indices = indices;
  79804. oldPos += component.count;
  79805. }
  79806. }
  79807. return components;
  79808. }
  79809. function clonePath(path) {
  79810. return { newPos: path.newPos, components: path.components.slice(0) };
  79811. }
  79812. var arrayDiff = new Diff();
  79813. var arrayDiff$1 = function (oldArr, newArr, callback) {
  79814. return arrayDiff.diff(oldArr, newArr, callback);
  79815. };
  79816. /**
  79817. * @file Manages elements that can be defined in <defs> in SVG,
  79818. * e.g., gradients, clip path, etc.
  79819. * @author Zhang Wenli
  79820. */
  79821. var MARK_UNUSED = '0';
  79822. var MARK_USED = '1';
  79823. /**
  79824. * Manages elements that can be defined in <defs> in SVG,
  79825. * e.g., gradients, clip path, etc.
  79826. *
  79827. * @class
  79828. * @param {number} zrId zrender instance id
  79829. * @param {SVGElement} svgRoot root of SVG document
  79830. * @param {string|string[]} tagNames possible tag names
  79831. * @param {string} markLabel label name to make if the element
  79832. * is used
  79833. */
  79834. function Definable(
  79835. zrId,
  79836. svgRoot,
  79837. tagNames,
  79838. markLabel,
  79839. domName
  79840. ) {
  79841. this._zrId = zrId;
  79842. this._svgRoot = svgRoot;
  79843. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  79844. this._markLabel = markLabel;
  79845. this._domName = domName || '_dom';
  79846. this.nextId = 0;
  79847. }
  79848. Definable.prototype.createElement = createElement;
  79849. /**
  79850. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  79851. *
  79852. * @param {boolean} isForceCreating if need to create when not exists
  79853. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  79854. * exist and isForceCreating is false
  79855. */
  79856. Definable.prototype.getDefs = function (isForceCreating) {
  79857. var svgRoot = this._svgRoot;
  79858. var defs = this._svgRoot.getElementsByTagName('defs');
  79859. if (defs.length === 0) {
  79860. // Not exist
  79861. if (isForceCreating) {
  79862. defs = svgRoot.insertBefore(
  79863. this.createElement('defs'), // Create new tag
  79864. svgRoot.firstChild // Insert in the front of svg
  79865. );
  79866. if (!defs.contains) {
  79867. // IE doesn't support contains method
  79868. defs.contains = function (el) {
  79869. var children = defs.children;
  79870. if (!children) {
  79871. return false;
  79872. }
  79873. for (var i = children.length - 1; i >= 0; --i) {
  79874. if (children[i] === el) {
  79875. return true;
  79876. }
  79877. }
  79878. return false;
  79879. };
  79880. }
  79881. return defs;
  79882. }
  79883. else {
  79884. return null;
  79885. }
  79886. }
  79887. else {
  79888. return defs[0];
  79889. }
  79890. };
  79891. /**
  79892. * Update DOM element if necessary.
  79893. *
  79894. * @param {Object|string} element style element. e.g., for gradient,
  79895. * it may be '#ccc' or {type: 'linear', ...}
  79896. * @param {Function|undefined} onUpdate update callback
  79897. */
  79898. Definable.prototype.update = function (element, onUpdate) {
  79899. if (!element) {
  79900. return;
  79901. }
  79902. var defs = this.getDefs(false);
  79903. if (element[this._domName] && defs.contains(element[this._domName])) {
  79904. // Update DOM
  79905. if (typeof onUpdate === 'function') {
  79906. onUpdate(element);
  79907. }
  79908. }
  79909. else {
  79910. // No previous dom, create new
  79911. var dom = this.add(element);
  79912. if (dom) {
  79913. element[this._domName] = dom;
  79914. }
  79915. }
  79916. };
  79917. /**
  79918. * Add gradient dom to defs
  79919. *
  79920. * @param {SVGElement} dom DOM to be added to <defs>
  79921. */
  79922. Definable.prototype.addDom = function (dom) {
  79923. var defs = this.getDefs(true);
  79924. defs.appendChild(dom);
  79925. };
  79926. /**
  79927. * Remove DOM of a given element.
  79928. *
  79929. * @param {SVGElement} element element to remove dom
  79930. */
  79931. Definable.prototype.removeDom = function (element) {
  79932. var defs = this.getDefs(false);
  79933. if (defs && element[this._domName]) {
  79934. defs.removeChild(element[this._domName]);
  79935. element[this._domName] = null;
  79936. }
  79937. };
  79938. /**
  79939. * Get DOMs of this element.
  79940. *
  79941. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  79942. */
  79943. Definable.prototype.getDoms = function () {
  79944. var defs = this.getDefs(false);
  79945. if (!defs) {
  79946. // No dom when defs is not defined
  79947. return [];
  79948. }
  79949. var doms = [];
  79950. each$1(this._tagNames, function (tagName) {
  79951. var tags = defs.getElementsByTagName(tagName);
  79952. // Note that tags is HTMLCollection, which is array-like
  79953. // rather than real array.
  79954. // So `doms.concat(tags)` add tags as one object.
  79955. doms = doms.concat([].slice.call(tags));
  79956. });
  79957. return doms;
  79958. };
  79959. /**
  79960. * Mark DOMs to be unused before painting, and clear unused ones at the end
  79961. * of the painting.
  79962. */
  79963. Definable.prototype.markAllUnused = function () {
  79964. var doms = this.getDoms();
  79965. var that = this;
  79966. each$1(doms, function (dom) {
  79967. dom[that._markLabel] = MARK_UNUSED;
  79968. });
  79969. };
  79970. /**
  79971. * Mark a single DOM to be used.
  79972. *
  79973. * @param {SVGElement} dom DOM to mark
  79974. */
  79975. Definable.prototype.markUsed = function (dom) {
  79976. if (dom) {
  79977. dom[this._markLabel] = MARK_USED;
  79978. }
  79979. };
  79980. /**
  79981. * Remove unused DOMs defined in <defs>
  79982. */
  79983. Definable.prototype.removeUnused = function () {
  79984. var defs = this.getDefs(false);
  79985. if (!defs) {
  79986. // Nothing to remove
  79987. return;
  79988. }
  79989. var doms = this.getDoms();
  79990. var that = this;
  79991. each$1(doms, function (dom) {
  79992. if (dom[that._markLabel] !== MARK_USED) {
  79993. // Remove gradient
  79994. defs.removeChild(dom);
  79995. }
  79996. });
  79997. };
  79998. /**
  79999. * Get SVG proxy.
  80000. *
  80001. * @param {Displayable} displayable displayable element
  80002. * @return {Path|Image|Text} svg proxy of given element
  80003. */
  80004. Definable.prototype.getSvgProxy = function (displayable) {
  80005. if (displayable instanceof Path) {
  80006. return svgPath;
  80007. }
  80008. else if (displayable instanceof ZImage) {
  80009. return svgImage;
  80010. }
  80011. else if (displayable instanceof Text) {
  80012. return svgText;
  80013. }
  80014. else {
  80015. return svgPath;
  80016. }
  80017. };
  80018. /**
  80019. * Get text SVG element.
  80020. *
  80021. * @param {Displayable} displayable displayable element
  80022. * @return {SVGElement} SVG element of text
  80023. */
  80024. Definable.prototype.getTextSvgElement = function (displayable) {
  80025. return displayable.__textSvgEl;
  80026. };
  80027. /**
  80028. * Get SVG element.
  80029. *
  80030. * @param {Displayable} displayable displayable element
  80031. * @return {SVGElement} SVG element
  80032. */
  80033. Definable.prototype.getSvgElement = function (displayable) {
  80034. return displayable.__svgEl;
  80035. };
  80036. /**
  80037. * @file Manages SVG gradient elements.
  80038. * @author Zhang Wenli
  80039. */
  80040. /**
  80041. * Manages SVG gradient elements.
  80042. *
  80043. * @class
  80044. * @extends Definable
  80045. * @param {number} zrId zrender instance id
  80046. * @param {SVGElement} svgRoot root of SVG document
  80047. */
  80048. function GradientManager(zrId, svgRoot) {
  80049. Definable.call(
  80050. this,
  80051. zrId,
  80052. svgRoot,
  80053. ['linearGradient', 'radialGradient'],
  80054. '__gradient_in_use__'
  80055. );
  80056. }
  80057. inherits(GradientManager, Definable);
  80058. /**
  80059. * Create new gradient DOM for fill or stroke if not exist,
  80060. * but will not update gradient if exists.
  80061. *
  80062. * @param {SvgElement} svgElement SVG element to paint
  80063. * @param {Displayable} displayable zrender displayable element
  80064. */
  80065. GradientManager.prototype.addWithoutUpdate = function (
  80066. svgElement,
  80067. displayable
  80068. ) {
  80069. if (displayable && displayable.style) {
  80070. var that = this;
  80071. each$1(['fill', 'stroke'], function (fillOrStroke) {
  80072. if (displayable.style[fillOrStroke]
  80073. && (displayable.style[fillOrStroke].type === 'linear'
  80074. || displayable.style[fillOrStroke].type === 'radial')
  80075. ) {
  80076. var gradient = displayable.style[fillOrStroke];
  80077. var defs = that.getDefs(true);
  80078. // Create dom in <defs> if not exists
  80079. var dom;
  80080. if (gradient._dom) {
  80081. // Gradient exists
  80082. dom = gradient._dom;
  80083. if (!defs.contains(gradient._dom)) {
  80084. // _dom is no longer in defs, recreate
  80085. that.addDom(dom);
  80086. }
  80087. }
  80088. else {
  80089. // New dom
  80090. dom = that.add(gradient);
  80091. }
  80092. that.markUsed(displayable);
  80093. var id = dom.getAttribute('id');
  80094. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  80095. }
  80096. });
  80097. }
  80098. };
  80099. /**
  80100. * Add a new gradient tag in <defs>
  80101. *
  80102. * @param {Gradient} gradient zr gradient instance
  80103. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  80104. * created DOM
  80105. */
  80106. GradientManager.prototype.add = function (gradient) {
  80107. var dom;
  80108. if (gradient.type === 'linear') {
  80109. dom = this.createElement('linearGradient');
  80110. }
  80111. else if (gradient.type === 'radial') {
  80112. dom = this.createElement('radialGradient');
  80113. }
  80114. else {
  80115. zrLog('Illegal gradient type.');
  80116. return null;
  80117. }
  80118. // Set dom id with gradient id, since each gradient instance
  80119. // will have no more than one dom element.
  80120. // id may exists before for those dirty elements, in which case
  80121. // id should remain the same, and other attributes should be
  80122. // updated.
  80123. gradient.id = gradient.id || this.nextId++;
  80124. dom.setAttribute('id', 'zr' + this._zrId
  80125. + '-gradient-' + gradient.id);
  80126. this.updateDom(gradient, dom);
  80127. this.addDom(dom);
  80128. return dom;
  80129. };
  80130. /**
  80131. * Update gradient.
  80132. *
  80133. * @param {Gradient} gradient zr gradient instance
  80134. */
  80135. GradientManager.prototype.update = function (gradient) {
  80136. var that = this;
  80137. Definable.prototype.update.call(this, gradient, function () {
  80138. var type = gradient.type;
  80139. var tagName = gradient._dom.tagName;
  80140. if (type === 'linear' && tagName === 'linearGradient'
  80141. || type === 'radial' && tagName === 'radialGradient'
  80142. ) {
  80143. // Gradient type is not changed, update gradient
  80144. that.updateDom(gradient, gradient._dom);
  80145. }
  80146. else {
  80147. // Remove and re-create if type is changed
  80148. that.removeDom(gradient);
  80149. that.add(gradient);
  80150. }
  80151. });
  80152. };
  80153. /**
  80154. * Update gradient dom
  80155. *
  80156. * @param {Gradient} gradient zr gradient instance
  80157. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  80158. * DOM to update
  80159. */
  80160. GradientManager.prototype.updateDom = function (gradient, dom) {
  80161. if (gradient.type === 'linear') {
  80162. dom.setAttribute('x1', gradient.x);
  80163. dom.setAttribute('y1', gradient.y);
  80164. dom.setAttribute('x2', gradient.x2);
  80165. dom.setAttribute('y2', gradient.y2);
  80166. }
  80167. else if (gradient.type === 'radial') {
  80168. dom.setAttribute('cx', gradient.x);
  80169. dom.setAttribute('cy', gradient.y);
  80170. dom.setAttribute('r', gradient.r);
  80171. }
  80172. else {
  80173. zrLog('Illegal gradient type.');
  80174. return;
  80175. }
  80176. if (gradient.global) {
  80177. // x1, x2, y1, y2 in range of 0 to canvas width or height
  80178. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  80179. }
  80180. else {
  80181. // x1, x2, y1, y2 in range of 0 to 1
  80182. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  80183. }
  80184. // Remove color stops if exists
  80185. dom.innerHTML = '';
  80186. // Add color stops
  80187. var colors = gradient.colorStops;
  80188. for (var i = 0, len = colors.length; i < len; ++i) {
  80189. var stop = this.createElement('stop');
  80190. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  80191. var color = colors[i].color;
  80192. if (color.indexOf('rgba' > -1)) {
  80193. // Fix Safari bug that stop-color not recognizing alpha #9014
  80194. var opacity = parse(color)[3];
  80195. var hex = toHex(color);
  80196. // stop-color cannot be color, since:
  80197. // The opacity value used for the gradient calculation is the
  80198. // *product* of the value of stop-opacity and the opacity of the
  80199. // value of stop-color.
  80200. // See https://www.w3.org/TR/SVG2/pservers.html#StopOpacityProperty
  80201. stop.setAttribute('stop-color', '#' + hex);
  80202. stop.setAttribute('stop-opacity', opacity);
  80203. }
  80204. else {
  80205. stop.setAttribute('stop-color', colors[i].color);
  80206. }
  80207. dom.appendChild(stop);
  80208. }
  80209. // Store dom element in gradient, to avoid creating multiple
  80210. // dom instances for the same gradient element
  80211. gradient._dom = dom;
  80212. };
  80213. /**
  80214. * Mark a single gradient to be used
  80215. *
  80216. * @param {Displayable} displayable displayable element
  80217. */
  80218. GradientManager.prototype.markUsed = function (displayable) {
  80219. if (displayable.style) {
  80220. var gradient = displayable.style.fill;
  80221. if (gradient && gradient._dom) {
  80222. Definable.prototype.markUsed.call(this, gradient._dom);
  80223. }
  80224. gradient = displayable.style.stroke;
  80225. if (gradient && gradient._dom) {
  80226. Definable.prototype.markUsed.call(this, gradient._dom);
  80227. }
  80228. }
  80229. };
  80230. /**
  80231. * @file Manages SVG clipPath elements.
  80232. * @author Zhang Wenli
  80233. */
  80234. /**
  80235. * Manages SVG clipPath elements.
  80236. *
  80237. * @class
  80238. * @extends Definable
  80239. * @param {number} zrId zrender instance id
  80240. * @param {SVGElement} svgRoot root of SVG document
  80241. */
  80242. function ClippathManager(zrId, svgRoot) {
  80243. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  80244. }
  80245. inherits(ClippathManager, Definable);
  80246. /**
  80247. * Update clipPath.
  80248. *
  80249. * @param {Displayable} displayable displayable element
  80250. */
  80251. ClippathManager.prototype.update = function (displayable) {
  80252. var svgEl = this.getSvgElement(displayable);
  80253. if (svgEl) {
  80254. this.updateDom(svgEl, displayable.__clipPaths, false);
  80255. }
  80256. var textEl = this.getTextSvgElement(displayable);
  80257. if (textEl) {
  80258. // Make another clipPath for text, since it's transform
  80259. // matrix is not the same with svgElement
  80260. this.updateDom(textEl, displayable.__clipPaths, true);
  80261. }
  80262. this.markUsed(displayable);
  80263. };
  80264. /**
  80265. * Create an SVGElement of displayable and create a <clipPath> of its
  80266. * clipPath
  80267. *
  80268. * @param {Displayable} parentEl parent element
  80269. * @param {ClipPath[]} clipPaths clipPaths of parent element
  80270. * @param {boolean} isText if parent element is Text
  80271. */
  80272. ClippathManager.prototype.updateDom = function (
  80273. parentEl,
  80274. clipPaths,
  80275. isText
  80276. ) {
  80277. if (clipPaths && clipPaths.length > 0) {
  80278. // Has clipPath, create <clipPath> with the first clipPath
  80279. var defs = this.getDefs(true);
  80280. var clipPath = clipPaths[0];
  80281. var clipPathEl;
  80282. var id;
  80283. var dom = isText ? '_textDom' : '_dom';
  80284. if (clipPath[dom]) {
  80285. // Use a dom that is already in <defs>
  80286. id = clipPath[dom].getAttribute('id');
  80287. clipPathEl = clipPath[dom];
  80288. // Use a dom that is already in <defs>
  80289. if (!defs.contains(clipPathEl)) {
  80290. // This happens when set old clipPath that has
  80291. // been previously removed
  80292. defs.appendChild(clipPathEl);
  80293. }
  80294. }
  80295. else {
  80296. // New <clipPath>
  80297. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  80298. ++this.nextId;
  80299. clipPathEl = this.createElement('clipPath');
  80300. clipPathEl.setAttribute('id', id);
  80301. defs.appendChild(clipPathEl);
  80302. clipPath[dom] = clipPathEl;
  80303. }
  80304. // Build path and add to <clipPath>
  80305. var svgProxy = this.getSvgProxy(clipPath);
  80306. if (clipPath.transform
  80307. && clipPath.parent.invTransform
  80308. && !isText
  80309. ) {
  80310. /**
  80311. * If a clipPath has a parent with transform, the transform
  80312. * of parent should not be considered when setting transform
  80313. * of clipPath. So we need to transform back from parent's
  80314. * transform, which is done by multiplying parent's inverse
  80315. * transform.
  80316. */
  80317. // Store old transform
  80318. var transform = Array.prototype.slice.call(
  80319. clipPath.transform
  80320. );
  80321. // Transform back from parent, and brush path
  80322. mul$1(
  80323. clipPath.transform,
  80324. clipPath.parent.invTransform,
  80325. clipPath.transform
  80326. );
  80327. svgProxy.brush(clipPath);
  80328. // Set back transform of clipPath
  80329. clipPath.transform = transform;
  80330. }
  80331. else {
  80332. svgProxy.brush(clipPath);
  80333. }
  80334. var pathEl = this.getSvgElement(clipPath);
  80335. clipPathEl.innerHTML = '';
  80336. /**
  80337. * Use `cloneNode()` here to appendChild to multiple parents,
  80338. * which may happend when Text and other shapes are using the same
  80339. * clipPath. Since Text will create an extra clipPath DOM due to
  80340. * different transform rules.
  80341. */
  80342. clipPathEl.appendChild(pathEl.cloneNode());
  80343. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  80344. if (clipPaths.length > 1) {
  80345. // Make the other clipPaths recursively
  80346. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  80347. }
  80348. }
  80349. else {
  80350. // No clipPath
  80351. if (parentEl) {
  80352. parentEl.setAttribute('clip-path', 'none');
  80353. }
  80354. }
  80355. };
  80356. /**
  80357. * Mark a single clipPath to be used
  80358. *
  80359. * @param {Displayable} displayable displayable element
  80360. */
  80361. ClippathManager.prototype.markUsed = function (displayable) {
  80362. var that = this;
  80363. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  80364. each$1(displayable.__clipPaths, function (clipPath) {
  80365. if (clipPath._dom) {
  80366. Definable.prototype.markUsed.call(that, clipPath._dom);
  80367. }
  80368. if (clipPath._textDom) {
  80369. Definable.prototype.markUsed.call(that, clipPath._textDom);
  80370. }
  80371. });
  80372. }
  80373. };
  80374. /**
  80375. * @file Manages SVG shadow elements.
  80376. * @author Zhang Wenli
  80377. */
  80378. /**
  80379. * Manages SVG shadow elements.
  80380. *
  80381. * @class
  80382. * @extends Definable
  80383. * @param {number} zrId zrender instance id
  80384. * @param {SVGElement} svgRoot root of SVG document
  80385. */
  80386. function ShadowManager(zrId, svgRoot) {
  80387. Definable.call(
  80388. this,
  80389. zrId,
  80390. svgRoot,
  80391. ['filter'],
  80392. '__filter_in_use__',
  80393. '_shadowDom'
  80394. );
  80395. }
  80396. inherits(ShadowManager, Definable);
  80397. /**
  80398. * Create new shadow DOM for fill or stroke if not exist,
  80399. * but will not update shadow if exists.
  80400. *
  80401. * @param {SvgElement} svgElement SVG element to paint
  80402. * @param {Displayable} displayable zrender displayable element
  80403. */
  80404. ShadowManager.prototype.addWithoutUpdate = function (
  80405. svgElement,
  80406. displayable
  80407. ) {
  80408. if (displayable && hasShadow(displayable.style)) {
  80409. var style = displayable.style;
  80410. // Create dom in <defs> if not exists
  80411. var dom;
  80412. if (style._shadowDom) {
  80413. // Gradient exists
  80414. dom = style._shadowDom;
  80415. var defs = this.getDefs(true);
  80416. if (!defs.contains(style._shadowDom)) {
  80417. // _shadowDom is no longer in defs, recreate
  80418. this.addDom(dom);
  80419. }
  80420. }
  80421. else {
  80422. // New dom
  80423. dom = this.add(displayable);
  80424. }
  80425. this.markUsed(displayable);
  80426. var id = dom.getAttribute('id');
  80427. svgElement.style.filter = 'url(#' + id + ')';
  80428. }
  80429. };
  80430. /**
  80431. * Add a new shadow tag in <defs>
  80432. *
  80433. * @param {Displayable} displayable zrender displayable element
  80434. * @return {SVGFilterElement} created DOM
  80435. */
  80436. ShadowManager.prototype.add = function (displayable) {
  80437. var dom = this.createElement('filter');
  80438. var style = displayable.style;
  80439. // Set dom id with shadow id, since each shadow instance
  80440. // will have no more than one dom element.
  80441. // id may exists before for those dirty elements, in which case
  80442. // id should remain the same, and other attributes should be
  80443. // updated.
  80444. style._shadowDomId = style._shadowDomId || this.nextId++;
  80445. dom.setAttribute('id', 'zr' + this._zrId
  80446. + '-shadow-' + style._shadowDomId);
  80447. this.updateDom(displayable, dom);
  80448. this.addDom(dom);
  80449. return dom;
  80450. };
  80451. /**
  80452. * Update shadow.
  80453. *
  80454. * @param {Displayable} displayable zrender displayable element
  80455. */
  80456. ShadowManager.prototype.update = function (svgElement, displayable) {
  80457. var style = displayable.style;
  80458. if (hasShadow(style)) {
  80459. var that = this;
  80460. Definable.prototype.update.call(this, displayable, function (style) {
  80461. that.updateDom(displayable, style._shadowDom);
  80462. });
  80463. }
  80464. else {
  80465. // Remove shadow
  80466. this.remove(svgElement, style);
  80467. }
  80468. };
  80469. /**
  80470. * Remove DOM and clear parent filter
  80471. */
  80472. ShadowManager.prototype.remove = function (svgElement, style) {
  80473. if (style._shadowDomId != null) {
  80474. this.removeDom(style);
  80475. svgElement.style.filter = '';
  80476. }
  80477. };
  80478. /**
  80479. * Update shadow dom
  80480. *
  80481. * @param {Displayable} displayable zrender displayable element
  80482. * @param {SVGFilterElement} dom DOM to update
  80483. */
  80484. ShadowManager.prototype.updateDom = function (displayable, dom) {
  80485. var domChild = dom.getElementsByTagName('feDropShadow');
  80486. if (domChild.length === 0) {
  80487. domChild = this.createElement('feDropShadow');
  80488. }
  80489. else {
  80490. domChild = domChild[0];
  80491. }
  80492. var style = displayable.style;
  80493. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  80494. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  80495. // TODO: textBoxShadowBlur is not supported yet
  80496. var offsetX, offsetY, blur, color;
  80497. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  80498. offsetX = style.shadowOffsetX || 0;
  80499. offsetY = style.shadowOffsetY || 0;
  80500. blur = style.shadowBlur;
  80501. color = style.shadowColor;
  80502. }
  80503. else if (style.textShadowBlur) {
  80504. offsetX = style.textShadowOffsetX || 0;
  80505. offsetY = style.textShadowOffsetY || 0;
  80506. blur = style.textShadowBlur;
  80507. color = style.textShadowColor;
  80508. }
  80509. else {
  80510. // Remove shadow
  80511. this.removeDom(dom, style);
  80512. return;
  80513. }
  80514. domChild.setAttribute('dx', offsetX / scaleX);
  80515. domChild.setAttribute('dy', offsetY / scaleY);
  80516. domChild.setAttribute('flood-color', color);
  80517. // Divide by two here so that it looks the same as in canvas
  80518. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  80519. var stdDx = blur / 2 / scaleX;
  80520. var stdDy = blur / 2 / scaleY;
  80521. var stdDeviation = stdDx + ' ' + stdDy;
  80522. domChild.setAttribute('stdDeviation', stdDeviation);
  80523. // Fix filter clipping problem
  80524. dom.setAttribute('x', '-100%');
  80525. dom.setAttribute('y', '-100%');
  80526. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  80527. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  80528. dom.appendChild(domChild);
  80529. // Store dom element in shadow, to avoid creating multiple
  80530. // dom instances for the same shadow element
  80531. style._shadowDom = dom;
  80532. };
  80533. /**
  80534. * Mark a single shadow to be used
  80535. *
  80536. * @param {Displayable} displayable displayable element
  80537. */
  80538. ShadowManager.prototype.markUsed = function (displayable) {
  80539. var style = displayable.style;
  80540. if (style && style._shadowDom) {
  80541. Definable.prototype.markUsed.call(this, style._shadowDom);
  80542. }
  80543. };
  80544. function hasShadow(style) {
  80545. // TODO: textBoxShadowBlur is not supported yet
  80546. return style
  80547. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  80548. || style.textShadowBlur || style.textShadowOffsetX
  80549. || style.textShadowOffsetY);
  80550. }
  80551. /**
  80552. * SVG Painter
  80553. * @module zrender/svg/Painter
  80554. */
  80555. function parseInt10$2(val) {
  80556. return parseInt(val, 10);
  80557. }
  80558. function getSvgProxy(el) {
  80559. if (el instanceof Path) {
  80560. return svgPath;
  80561. }
  80562. else if (el instanceof ZImage) {
  80563. return svgImage;
  80564. }
  80565. else if (el instanceof Text) {
  80566. return svgText;
  80567. }
  80568. else {
  80569. return svgPath;
  80570. }
  80571. }
  80572. function checkParentAvailable(parent, child) {
  80573. return child && parent && child.parentNode !== parent;
  80574. }
  80575. function insertAfter(parent, child, prevSibling) {
  80576. if (checkParentAvailable(parent, child) && prevSibling) {
  80577. var nextSibling = prevSibling.nextSibling;
  80578. nextSibling ? parent.insertBefore(child, nextSibling)
  80579. : parent.appendChild(child);
  80580. }
  80581. }
  80582. function prepend(parent, child) {
  80583. if (checkParentAvailable(parent, child)) {
  80584. var firstChild = parent.firstChild;
  80585. firstChild ? parent.insertBefore(child, firstChild)
  80586. : parent.appendChild(child);
  80587. }
  80588. }
  80589. function remove$1(parent, child) {
  80590. if (child && parent && child.parentNode === parent) {
  80591. parent.removeChild(child);
  80592. }
  80593. }
  80594. function getTextSvgElement(displayable) {
  80595. return displayable.__textSvgEl;
  80596. }
  80597. function getSvgElement(displayable) {
  80598. return displayable.__svgEl;
  80599. }
  80600. /**
  80601. * @alias module:zrender/svg/Painter
  80602. * @constructor
  80603. * @param {HTMLElement} root 绘图容器
  80604. * @param {module:zrender/Storage} storage
  80605. * @param {Object} opts
  80606. */
  80607. var SVGPainter = function (root, storage, opts, zrId) {
  80608. this.root = root;
  80609. this.storage = storage;
  80610. this._opts = opts = extend({}, opts || {});
  80611. var svgRoot = createElement('svg');
  80612. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  80613. svgRoot.setAttribute('version', '1.1');
  80614. svgRoot.setAttribute('baseProfile', 'full');
  80615. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  80616. this.gradientManager = new GradientManager(zrId, svgRoot);
  80617. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  80618. this.shadowManager = new ShadowManager(zrId, svgRoot);
  80619. var viewport = document.createElement('div');
  80620. viewport.style.cssText = 'overflow:hidden;position:relative';
  80621. this._svgRoot = svgRoot;
  80622. this._viewport = viewport;
  80623. root.appendChild(viewport);
  80624. viewport.appendChild(svgRoot);
  80625. this.resize(opts.width, opts.height);
  80626. this._visibleList = [];
  80627. };
  80628. SVGPainter.prototype = {
  80629. constructor: SVGPainter,
  80630. getType: function () {
  80631. return 'svg';
  80632. },
  80633. getViewportRoot: function () {
  80634. return this._viewport;
  80635. },
  80636. getViewportRootOffset: function () {
  80637. var viewportRoot = this.getViewportRoot();
  80638. if (viewportRoot) {
  80639. return {
  80640. offsetLeft: viewportRoot.offsetLeft || 0,
  80641. offsetTop: viewportRoot.offsetTop || 0
  80642. };
  80643. }
  80644. },
  80645. refresh: function () {
  80646. var list = this.storage.getDisplayList(true);
  80647. this._paintList(list);
  80648. },
  80649. setBackgroundColor: function (backgroundColor) {
  80650. // TODO gradient
  80651. this._viewport.style.background = backgroundColor;
  80652. },
  80653. _paintList: function (list) {
  80654. this.gradientManager.markAllUnused();
  80655. this.clipPathManager.markAllUnused();
  80656. this.shadowManager.markAllUnused();
  80657. var svgRoot = this._svgRoot;
  80658. var visibleList = this._visibleList;
  80659. var listLen = list.length;
  80660. var newVisibleList = [];
  80661. var i;
  80662. for (i = 0; i < listLen; i++) {
  80663. var displayable = list[i];
  80664. var svgProxy = getSvgProxy(displayable);
  80665. var svgElement = getSvgElement(displayable)
  80666. || getTextSvgElement(displayable);
  80667. if (!displayable.invisible) {
  80668. if (displayable.__dirty) {
  80669. svgProxy && svgProxy.brush(displayable);
  80670. // Update clipPath
  80671. this.clipPathManager.update(displayable);
  80672. // Update gradient and shadow
  80673. if (displayable.style) {
  80674. this.gradientManager
  80675. .update(displayable.style.fill);
  80676. this.gradientManager
  80677. .update(displayable.style.stroke);
  80678. this.shadowManager
  80679. .update(svgElement, displayable);
  80680. }
  80681. displayable.__dirty = false;
  80682. }
  80683. newVisibleList.push(displayable);
  80684. }
  80685. }
  80686. var diff = arrayDiff$1(visibleList, newVisibleList);
  80687. var prevSvgElement;
  80688. // First do remove, in case element moved to the head and do remove
  80689. // after add
  80690. for (i = 0; i < diff.length; i++) {
  80691. var item = diff[i];
  80692. if (item.removed) {
  80693. for (var k = 0; k < item.count; k++) {
  80694. var displayable = visibleList[item.indices[k]];
  80695. var svgElement = getSvgElement(displayable);
  80696. var textSvgElement = getTextSvgElement(displayable);
  80697. remove$1(svgRoot, svgElement);
  80698. remove$1(svgRoot, textSvgElement);
  80699. }
  80700. }
  80701. }
  80702. for (i = 0; i < diff.length; i++) {
  80703. var item = diff[i];
  80704. if (item.added) {
  80705. for (var k = 0; k < item.count; k++) {
  80706. var displayable = newVisibleList[item.indices[k]];
  80707. var svgElement = getSvgElement(displayable);
  80708. var textSvgElement = getTextSvgElement(displayable);
  80709. prevSvgElement
  80710. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  80711. : prepend(svgRoot, svgElement);
  80712. if (svgElement) {
  80713. insertAfter(svgRoot, textSvgElement, svgElement);
  80714. }
  80715. else if (prevSvgElement) {
  80716. insertAfter(
  80717. svgRoot, textSvgElement, prevSvgElement
  80718. );
  80719. }
  80720. else {
  80721. prepend(svgRoot, textSvgElement);
  80722. }
  80723. // Insert text
  80724. insertAfter(svgRoot, textSvgElement, svgElement);
  80725. prevSvgElement = textSvgElement || svgElement
  80726. || prevSvgElement;
  80727. this.gradientManager
  80728. .addWithoutUpdate(svgElement, displayable);
  80729. this.shadowManager
  80730. .addWithoutUpdate(prevSvgElement, displayable);
  80731. this.clipPathManager.markUsed(displayable);
  80732. }
  80733. }
  80734. else if (!item.removed) {
  80735. for (var k = 0; k < item.count; k++) {
  80736. var displayable = newVisibleList[item.indices[k]];
  80737. prevSvgElement =
  80738. svgElement =
  80739. getTextSvgElement(displayable)
  80740. || getSvgElement(displayable)
  80741. || prevSvgElement;
  80742. this.gradientManager.markUsed(displayable);
  80743. this.gradientManager
  80744. .addWithoutUpdate(svgElement, displayable);
  80745. this.shadowManager.markUsed(displayable);
  80746. this.shadowManager
  80747. .addWithoutUpdate(svgElement, displayable);
  80748. this.clipPathManager.markUsed(displayable);
  80749. }
  80750. }
  80751. }
  80752. this.gradientManager.removeUnused();
  80753. this.clipPathManager.removeUnused();
  80754. this.shadowManager.removeUnused();
  80755. this._visibleList = newVisibleList;
  80756. },
  80757. _getDefs: function (isForceCreating) {
  80758. var svgRoot = this._svgRoot;
  80759. var defs = this._svgRoot.getElementsByTagName('defs');
  80760. if (defs.length === 0) {
  80761. // Not exist
  80762. if (isForceCreating) {
  80763. var defs = svgRoot.insertBefore(
  80764. createElement('defs'), // Create new tag
  80765. svgRoot.firstChild // Insert in the front of svg
  80766. );
  80767. if (!defs.contains) {
  80768. // IE doesn't support contains method
  80769. defs.contains = function (el) {
  80770. var children = defs.children;
  80771. if (!children) {
  80772. return false;
  80773. }
  80774. for (var i = children.length - 1; i >= 0; --i) {
  80775. if (children[i] === el) {
  80776. return true;
  80777. }
  80778. }
  80779. return false;
  80780. };
  80781. }
  80782. return defs;
  80783. }
  80784. else {
  80785. return null;
  80786. }
  80787. }
  80788. else {
  80789. return defs[0];
  80790. }
  80791. },
  80792. resize: function (width, height) {
  80793. var viewport = this._viewport;
  80794. // FIXME Why ?
  80795. viewport.style.display = 'none';
  80796. // Save input w/h
  80797. var opts = this._opts;
  80798. width != null && (opts.width = width);
  80799. height != null && (opts.height = height);
  80800. width = this._getSize(0);
  80801. height = this._getSize(1);
  80802. viewport.style.display = '';
  80803. if (this._width !== width || this._height !== height) {
  80804. this._width = width;
  80805. this._height = height;
  80806. var viewportStyle = viewport.style;
  80807. viewportStyle.width = width + 'px';
  80808. viewportStyle.height = height + 'px';
  80809. var svgRoot = this._svgRoot;
  80810. // Set width by 'svgRoot.width = width' is invalid
  80811. svgRoot.setAttribute('width', width);
  80812. svgRoot.setAttribute('height', height);
  80813. }
  80814. },
  80815. /**
  80816. * 获取绘图区域宽度
  80817. */
  80818. getWidth: function () {
  80819. return this._width;
  80820. },
  80821. /**
  80822. * 获取绘图区域高度
  80823. */
  80824. getHeight: function () {
  80825. return this._height;
  80826. },
  80827. _getSize: function (whIdx) {
  80828. var opts = this._opts;
  80829. var wh = ['width', 'height'][whIdx];
  80830. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  80831. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  80832. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  80833. if (opts[wh] != null && opts[wh] !== 'auto') {
  80834. return parseFloat(opts[wh]);
  80835. }
  80836. var root = this.root;
  80837. // IE8 does not support getComputedStyle, but it use VML.
  80838. var stl = document.defaultView.getComputedStyle(root);
  80839. return (
  80840. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  80841. - (parseInt10$2(stl[plt]) || 0)
  80842. - (parseInt10$2(stl[prb]) || 0)
  80843. ) | 0;
  80844. },
  80845. dispose: function () {
  80846. this.root.innerHTML = '';
  80847. this._svgRoot =
  80848. this._viewport =
  80849. this.storage =
  80850. null;
  80851. },
  80852. clear: function () {
  80853. if (this._viewport) {
  80854. this.root.removeChild(this._viewport);
  80855. }
  80856. },
  80857. pathToDataUrl: function () {
  80858. this.refresh();
  80859. var html = this._svgRoot.outerHTML;
  80860. return 'data:image/svg+xml;charset=UTF-8,' + html;
  80861. }
  80862. };
  80863. // Not supported methods
  80864. function createMethodNotSupport$1(method) {
  80865. return function () {
  80866. zrLog('In SVG mode painter not support method "' + method + '"');
  80867. };
  80868. }
  80869. // Unsuppoted methods
  80870. each$1([
  80871. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  80872. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  80873. 'toDataURL', 'pathToImage'
  80874. ], function (name) {
  80875. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  80876. });
  80877. registerPainter('svg', SVGPainter);
  80878. /*
  80879. * Licensed to the Apache Software Foundation (ASF) under one
  80880. * or more contributor license agreements. See the NOTICE file
  80881. * distributed with this work for additional information
  80882. * regarding copyright ownership. The ASF licenses this file
  80883. * to you under the Apache License, Version 2.0 (the
  80884. * "License"); you may not use this file except in compliance
  80885. * with the License. You may obtain a copy of the License at
  80886. *
  80887. * http://www.apache.org/licenses/LICENSE-2.0
  80888. *
  80889. * Unless required by applicable law or agreed to in writing,
  80890. * software distributed under the License is distributed on an
  80891. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  80892. * KIND, either express or implied. See the License for the
  80893. * specific language governing permissions and limitations
  80894. * under the License.
  80895. */
  80896. // Import all charts and components
  80897. exports.version = version;
  80898. exports.dependencies = dependencies;
  80899. exports.PRIORITY = PRIORITY;
  80900. exports.init = init;
  80901. exports.connect = connect;
  80902. exports.disConnect = disConnect;
  80903. exports.disconnect = disconnect;
  80904. exports.dispose = dispose;
  80905. exports.getInstanceByDom = getInstanceByDom;
  80906. exports.getInstanceById = getInstanceById;
  80907. exports.registerTheme = registerTheme;
  80908. exports.registerPreprocessor = registerPreprocessor;
  80909. exports.registerProcessor = registerProcessor;
  80910. exports.registerPostUpdate = registerPostUpdate;
  80911. exports.registerAction = registerAction;
  80912. exports.registerCoordinateSystem = registerCoordinateSystem;
  80913. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  80914. exports.registerLayout = registerLayout;
  80915. exports.registerVisual = registerVisual;
  80916. exports.registerLoading = registerLoading;
  80917. exports.extendComponentModel = extendComponentModel;
  80918. exports.extendComponentView = extendComponentView;
  80919. exports.extendSeriesModel = extendSeriesModel;
  80920. exports.extendChartView = extendChartView;
  80921. exports.setCanvasCreator = setCanvasCreator;
  80922. exports.registerMap = registerMap;
  80923. exports.getMap = getMap;
  80924. exports.dataTool = dataTool;
  80925. exports.zrender = zrender;
  80926. exports.number = number;
  80927. exports.format = format;
  80928. exports.throttle = throttle;
  80929. exports.helper = helper;
  80930. exports.matrix = matrix;
  80931. exports.vector = vector;
  80932. exports.color = color;
  80933. exports.parseGeoJSON = parseGeoJson$1;
  80934. exports.parseGeoJson = parseGeoJson;
  80935. exports.util = ecUtil;
  80936. exports.graphic = graphic$1;
  80937. exports.List = List;
  80938. exports.Model = Model;
  80939. exports.Axis = Axis;
  80940. exports.env = env$1;
  80941. })));
  80942. //# sourceMappingURL=echarts-en.js.map